简体   繁体   中英

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,

[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

Starting with a side note:

Don't use $Input as a custom variable as it is a preserved automatic variable

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).

Instead
You might want to use the Select-String cmdlet with the -AllMatches switch which counts all the matches:

[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:

[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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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