powershell Foreach-对象

cul*_*ter 3 powershell powershell-2.0 powershell-remoting

我有这个数组(简化):

$v = 3,5,3,6,8,3,5,7
Run Code Online (Sandbox Code Playgroud)

我需要检查所有值是否都高于 3。我认为 Foreach 或 Foreach-Object 将适合此任务,但我无法弄清楚它的工作方式。

我已经尝试过类似的方法,但它不起作用。

$v | Foreach-Object (if($_ -lt 10){Write-Host "$_ lt 10"})
Run Code Online (Sandbox Code Playgroud)

编辑:

感谢你们!我将声明更改为:

$v | Foreach-Object {if($_ -lt 10){$check_value = "True"}}
Run Code Online (Sandbox Code Playgroud)

它现在正在工作,但我刚刚意识到,简单化的数组不是一个好主意。我使用的数组中的数据是从 MS SQL 数据库中获取的。如果我在屏幕上显示数组,我会得到数字,但数据类型是 System.Data.DataRow,我无法将其与数字进行比较。我收到错误消息:

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".".
Run Code Online (Sandbox Code Playgroud)

编辑2:

飞溅的碎片:

我正在使用您的代码,一切正常,但我无法通过此比较:

$rowsGreaterThanThree.Count -eq $v.Count
Run Code Online (Sandbox Code Playgroud)

$rowsGreaterThanThree 的值为:

处理器时间

0.00127998361620918
1.53972183002211
0.00127998361620918 0.00127998361620918
0.00127998361620918 1.53972183002211
0.0012799 8361620918 0.00127998361620918 0.00127998361620918 3.1262399841282 0 0 0 0 0









$v 包含:

处理器时间

0.00127998361620918
1.53972183002211
0.00127998361620918 0.00127998361620918
0.00127998361620918 1.53972183002211
0.0012799 8361620918 0.00127998361620918 0.00127998361620918 3.1262399841282 0 0 0 0 0









值是相同的,但 $v 中的“ProcessorTime”下方多了一个空白行(此处不可见)。$rowsGreaterThanThree.Count 中的 Count 给出 16 而不是 15。

我的代码:(我将 -gt 修改为 -ge,因为有零。在工作版本中,我想检查处理器在一段时间内的负载是否超过 95%。)

$warning_values = @( $check | Where-Object { $_.ProcessorTime -ge 0 } )
if($warning_values.Count -eq $check.Count )
    {
        Write-Host -ForegroundColor "Warning!"
        }
        else { Write-Host "nothing"}
Run Code Online (Sandbox Code Playgroud)

Sha*_*evy 5

简单的 :)

PS> $v -gt 3
5
6
8
5
7
Run Code Online (Sandbox Code Playgroud)

或者

$v | Where-Object { $_ -gt 3 }
Run Code Online (Sandbox Code Playgroud)