Reputation: 5697
I have this array (simplyfied):
$v = 3,5,3,6,8,3,5,7
I need to check if all the values are higher than 3. I think that Foreach or Foreach-Object will be suitable for this task, but I can't figure out the way it works.
I've tried something like this, but it doesn't work.
$v | Foreach-Object (if($_ -lt 10){Write-Host "$_ lt 10"})
EDIT:
Thank you, guys! I changed the statement to:
$v | Foreach-Object {if($_ -lt 10){$check_value = "True"}}
It's working now, but I just realized, that the simplyfied array wasn't a good idea. The data in array I'm using are grabbed from MS SQL database. If I display the array on screen, I get numbers, but the type of data is System.Data.DataRow, which I can not compare to number. I get error msg:
Bad argument to operator '-lt': Could not compare "System.Data.DataRow" to "95". Error: "Cannot convert the "95" value of type "System.Int32" to type "System.Data.DataRow".".
EDIT2:
splatteredbits:
I'm using your code, everything works fine, but I cannot pass through this comparison:
$rowsGreaterThanThree.Count -eq $v.Count
the values of $rowsGreaterThanThree are:
0.00127998361620918
1.53972183002211
0.00127998361620918
0.00127998361620918
0.00127998361620918
1.53972183002211
0.00127998361620918
0.00127998361620918
0.00127998361620918
3.1262399841282
0
0
0
0
0
and $v contains:
0.00127998361620918
1.53972183002211
0.00127998361620918
0.00127998361620918
0.00127998361620918
1.53972183002211
0.00127998361620918
0.00127998361620918
0.00127998361620918
3.1262399841282
0
0
0
0
0
The values are the same, but there is one more blank row in $v beneath the "ProcessorTime"(here it's not visible). Count gives 16 instead of 15 in $rowsGreaterThanThree.Count.
My code: (I modyfied -gt to -ge, because there are zeros. In working version I want to check if processor is loaded above 95% for a time period.)
$warning_values = @( $check | Where-Object { $_.ProcessorTime -ge 0 } )
if($warning_values.Count -eq $check.Count )
{
Write-Host -ForegroundColor "Warning!"
}
else { Write-Host "nothing"}
Upvotes: 3
Views: 4884
Reputation: 26769
Shay's example is perfect: use Where-Object
to filter items from an array.
Because your objects are DataRow objects, you'll need to filter on the column:
$rowsGreaterThanThree = @( $v | Where-Object { $_.ColumnName -gt 3 } )
if( $rowsGreaterThanThree.Count -eq $v.Count )
{
Write-Host "All the rows are greater than 3!"
}
Replace ColumnName
with the name of the column which contains the actual value you want to filter on.
You can also do this in SQL with a WHERE
clause:
SELECT * FROM Table WHERE Column > 3
Then, you're getting just the values you want out of SQL Server. Of course, you may need the unfiltered values in your script, too.
Upvotes: 2
Reputation: 126872
Simple :)
PS> $v -gt 3
5
6
8
5
7
Or
$v | Where-Object { $_ -gt 3 }
Upvotes: 5