验证数组的成员

问题描述 投票:1回答:1

我有一个字符串,我从XML中提取,应该包含逗号分隔的整数值。目前我正在使用它将字符串转换为数组并测试数组的每个成员以查看它是否为Int。最终我仍然想要一个数组,因为我还有一组默认的成功代码,我想组合它们。也就是说,我从未发现这种将测试条件设置为true然后循环的模式,并可能将其设置为false以使其变得优雅。所以,我想知道是否有更好的方法。我的意思是,这很有效,而且速度很快,而且代码很容易阅读,所以从某种意义上来说没有理由改变它,但如果有更好的方法......

$supplamentalSuccessCode = ($string.Split(',')).Trim()
$validSupplamentalSuccessCode = $true
foreach ($code in $supplamentalSuccessCode) {
   if ($code -as [int] -isNot [int]) {
      $validSupplamentalSuccessCode = $false
   }
}

编辑:为了澄清,这个例子是相当具体的,但我很好奇一个更通用的解决方案。因此,假设数组可能包含需要根据查找表检查的值,或者需要使用Test-Path检查的本地驱动器路径。所以更一般地说,我想知道是否有比Set变量更好的解决方案true,foreach,如果测试失败则设置变量false逻辑。此外,我玩了一个While循环,但在大多数情况下,我想找到所有错误的值,而不是第一个错误的退出验证,所以我可以在日志中为用户提供完整的错误。因此我一直在使用ForEach循环方法。

arrays powershell validation
1个回答
1
投票

在PSv4 +中,您可以获得.Where() collection "operator"的帮助来确定所有无效值:

这是一个简化的例子:

# Sample input.
$string = '10, no, 20, stillno, -1'

# Split the list into an array.
$codes = ($string.Split(',')).Trim()

# Test all array members with a script block passed to. Where()  
# As usual, $_ refers to the element at hand.
# You can perform whatever validation is necessary inside the block.
$invalidCodes = $codes.Where({ $null -eq ($_ -as [int]) })

$invalidCodes # output the invalid codes, if any

以上产量:

no
stillno

请注意,.Where()返回的不是常规PowerShell数组([object[]]),而是[System.Collections.ObjectModel.Collection[PSObject]]的实例,但在大多数情况下,差异无关紧要。


与PSv2兼容的解决方案有点麻烦:

# Sample input.
$string = '10, no, 20, stillno, -1'

# Split the list into an array.
# Note: In PSv*3* you could use the simpler $codes = ($string.Split(',')).Trim() 
#       as in the PSv4+ solution.
$codes = foreach ($code in $string.Split(',')) { $code.Trim() }

# Emulate the behavior of .Where() with a foreach loop:
# Note that do you get an [object[]] instance back this time.
$invalidCodes = foreach ($code in $codes) { if ($null -eq ($code -as [int])) { $code } }
© www.soinside.com 2019 - 2024. All rights reserved.