简体   繁体   English

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

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

I have an integer array like below and I wanted to count number of 1's in that array in powershell, Can anyone help me here please,我有一个 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"

It gives me only 5 1's in that array but expected answer is 10. Any help would be appreciated它在该数组中只给了我 5 个 1,但预期的答案是 10。任何帮助将不胜感激

Starting with a side note:从旁注开始:

Don't use $Input as a custom variable as it is a preserved automatic variable不要将$Input用作自定义变量,因为它是保留的自动变量

For what you are trying:对于您正在尝试的内容:
You iterating trough an array and check whether each item (with will automatically type cast to a string) is -like a 1 preceded by any number of characters and succeeded by any number of characters which is either true or false (and not the total number of ones in the string).您遍历一个数组并检查每个项目(将自动类型转换为字符串)是否-like一个1前面有任意数量的字符,然后是任意数量的字符,无论是真还是假(而不是总数字符串中的一个)。

Instead反而
You might want to use the Select-String cmdlet with the -AllMatches switch which counts all the matches:您可能希望将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"

In fact, thanks to the PowerShell member enumeration feature, you do not even have to iterate through each array item for this, and just simplify it to this:事实上,由于 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

I solved the above issue with below script,我用下面的脚本解决了上述问题,

[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