因此下面的Object and Foreach循环恰好完成了我需要做的事情,即找出每行是偶数还是奇数。
$anon = @()
$anon += [PSCustomObject] @{ Name = "i am a thing" ; Location = "1" ; Value = $false }
$anon += [PSCustomObject] @{ Name = "I also do stuff" ; Location = "2" ; Value = $false }
$anon += [PSCustomObject] @{ Name = "I have been known to do stuff" ; Location = "3" ; Value = $true }
$anon += [PSCustomObject] @{ Name = "I do nothing" ; Location = "4" ; Value = $true }
Foreach ( $anonauth in $anon ) {
If ( $anonauth.location % 2 -eq 0 ) {
"I am even, and will do X"
}
Else {
"I am odd, and will do y"
}
}
我想知道的是,有没有一种方法可以执行相同的任务而没有“位置”作为IF偶/奇的参考点?
我的对象中有四行,是否可以使用[0],[1],[2],[3]作为计算参考?
这有意义吗?当我确定它已经存在时,拥有参考号似乎是一种浪费?
答案 0 :(得分:2)
您可以使用“旧学校” for-loop:
$anon = @()
$anon += [PSCustomObject] @{ Name = "i am a thing" ; Value = $false }
$anon += [PSCustomObject] @{ Name = "I also do stuff" ; Value = $false }
$anon += [PSCustomObject] @{ Name = "I have been known to do stuff" ; Value = $true }
$anon += [PSCustomObject] @{ Name = "I do nothing"; Value = $true }
for( $i =0; $i -lt $anon.Count; $i++ ) {
If ( $i % 2 -eq 0 ) {
"I am even, and will do X"
}
Else {
"I am odd, and will do y"
}
}
答案 1 :(得分:1)
您可以在foreach循环中实现一些$counter
变量,以跟踪到目前为止已迭代的项目数:
$counter = 0
Foreach ( $anonauth in $anon ) {
$counter += 1 # or, use $counter++
If ( $counter % 2 -eq 0 ) {
"I am even, and will do X"
}
Else {
"I am odd, and will do y"
}
}