我想在PowerShell中计算一个数组中小于10的数字,我必须使用foreach循环。
cls
$a = 0..9
$i = 0
foreach ($element in $a) {
if ($element -gt 2)
{
$i = $i + 1
Write-Host $i
}
}
更改 -gt
("大于")至 -lt
("小于"),并改变 2
到 10
:
foreach ($element in $a) {
if ($element -lt 10)
{
$i = $i + 1
}
}
Write-Host "Counted $i numbers under 10"
这里有另一种获得计数的方法。它过滤出不小于限制的项目,将它们发送到另一个$Var,然后使用 .Count
最后,它显示了小于极限值的数字列表。
代码& 注释似乎很清楚,但如果你有问题,请问...[。咧嘴一笑]
# only the last 3 items are NOT less than 10
$NumberList = @(1,3,5,7,9,1,1,4,0,-1,-666,111,666,10)
$Limit = 10
$TotalNumbers = $NumberList.Count
# a ".Where()" method call would be more obvious
# so would piping to `Where-Object`
# however, the requirement is to use a "foreach" loop [*grin*]
$LessThanLimit = foreach ($NL_Item in $NumberList)
{
if ($NL_Item -lt $Limit)
{
$NL_Item
}
}
'Total Numbers = {0}' -f $NumberList.Count
'Numbers less than [ {0,3} ] = {1}' -f $Limit, $LessThanLimit.Count
"$LessThanLimit"
产量...
Total Numbers = 14
Numbers less than [ 10 ] = 11
1 3 5 7 9 1 1 4 0 -1 -666