繁体   English   中英

Powershell:从 integer 数组中查找特定数值的出现次数

[英]Powershell: Find number of occurrences of a specific numeric value from an integer array

我有一个 integer 数组,如下所示,我想在 powershell 中计算该数组中 1 的数量,有人可以帮我吗?

[array]$inputs = 81,11,101,1811,1981
$count = 0
foreach($input in $inputs)
{       
Write-Host "Processing element $input"
$count += ($input -like "*1*" | Measure-Object).Count 
}
Write-Host "Number of 1's in the given array is $count"

它在该数组中只给了我 5 个 1,但预期的答案是 10。任何帮助将不胜感激

从旁注开始:

不要将$Input用作自定义变量,因为它是保留的自动变量

对于您正在尝试的内容:
您遍历一个数组并检查每个项目(将自动类型转换为字符串)是否-like一个1前面有任意数量的字符,然后是任意数量的字符,无论是真还是假(而不是总数字符串中的一个)。

反而
您可能希望将Select-String cmdlet 与-AllMatches开关一起使用,该开关会计算所有匹配项:

[array]$inputs = 81,11,101,1811,1981
$count = 0
foreach($i in $inputs)
{       
Write-Host "Processing element $input"
$count += ($i | Select-String 1 -AllMatches).Matches.Count 
}
Write-Host "Number of 1's in the given array is $count"

事实上,由于 PowerShell成员枚举功能,您甚至不必为此遍历每个数组项,只需将其简化为:

[array]$inputs = 81,11,101,1811,1981
$count = ($Inputs | Select-String 1 -AllMatches).Matches.Count
Write-Host "Number of 1's in the given array is $count"

Number of 1's in the given array is 10

我用下面的脚本解决了上述问题,

[string]$inputs = 81,11,101,1811,1981
$count = 0
foreach($i in $inputs.ToCharArray())
{  
    if($i -eq "1")   
    {$count++}  
 
}
Write-Host "Number of 1's in the given array is $count"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM