0

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

iRon
  • 20,463
  • 10
  • 53
  • 79

2 Answers2

0

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
iRon
  • 20,463
  • 10
  • 53
  • 79
  • Please [decide if the answer is helpful, and then...](https://stackoverflow.com/help/someone-answers) – iRon Dec 07 '20 at 17:09
  • Thanks for the solution and suggestion. It works also I have solved this issue with below script, Is it a right approach, [string]$inputs = 89,89,99,909,9899,9989,9.09 $count = 0 foreach($i in $inputs.ToCharArray()) { if($i -eq "9") {$count++} } Write-Host "Number of 9's in the given array is $count" – Thiyagarajan vasu devan Dec 08 '20 at 11:50
0

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"