首页 > 解决方案 > Powershell:从整数数组中查找特定数值的出现次数

问题描述

我有一个如下所示的整数数组,我想在 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。任何帮助将不胜感激

标签: arrayspowershellinteger

解决方案


从旁注开始:

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

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

相反
,您可能希望将Select-Stringcmdlet 与-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

推荐阅读