【问题标题】:Powershell Nested Foreach loop giving incorrect resultsPowershell嵌套的Foreach循环给出不正确的结果
【发布时间】:2013-06-26 15:35:29
【问题描述】:

我有两个数组 $newUsers 和 $oldUsers 已经在我编写的脚本中填充了用户 ID。我的下一个目标是检查 $newUsers 中的用户 ID 是否存在于 $oldUsers 中。如果是,则显示语句 Write-Host "New User_id $rowNew found in Old user list" else display Write-Host "New User_id $rowNew Notfound in Old user list"

下面是我使用的逻辑和我得到的输出。

foreach ($rowNew in $newusers){ 
           foreach ($rowOld in $oldusers){
                 if ($rowNew -ieq $rowOld){ 
                      Write-Host "New User_id $rowNew found in Old user list"
                 } else {
                   Write-Host "New User_id $rowNew Notfound in Old user list"   
                 }
            }
        }

--结果

New User_id fadb274 found in Old user list
New User_id fadb274 Notfound in Old user list
New User_id fadb274 Notfound in Old user list
New User_id fadb274 Notfound in Old user list
New User_id fadb274 Notfound in Old user list
New User_id fadb274 Notfound in Old user list
New User_id fadb274 Notfound in Old user list
New User_id fadb274 Notfound in Old user list
New User_id fad8878 found in Old user list
New User_id fad8878 Notfound in Old user list
New User_id fad8878 Notfound in Old user list
New User_id fad8878 Notfound in Old user list

不知道为什么我会得到上述结果,我不应该为每个用户 ID 得到一个结果。谁能帮助我了解我需要在上面的代码 sn-p 中更改什么?

【问题讨论】:

  • 我建议使用compare-object cmdlet。

标签: powershell foreach


【解决方案1】:

我认为问题在于您试图将一个文件中的每个项目与另一个文件中的每个其他项目匹配,因此每次运行外循环都会导致一个可能的匹配项和大量不匹配项。

为什么不像这样使用比较对象:

Compare-Object -ReferenceObject $oldusers -DifferenceObject $newusers -IncludeEqual | % {
  if($_.SideIndicator -eq '==') {$f = 'found'} else {$f = 'NotFound'}
  if($_.SideIndicator -eq '<=') {$a = 'Old'} 
  if($_.SideIndicator -eq '=>') {$a = 'New'}
  "New User_id $($_.InputObject) $f in $a user list"
}

另一种选择是只做一个循环并使用 -contains 而不是 -ieq。

【讨论】:

  • 谢谢戴夫!!它起作用了,为了在我的脚本中对这些用户 ID 进行进一步分析,我将如何在 foreach-object 循环中将找到的用户 ID 分配到一个数组中而不将找到的用户 ID 分配到另一个数组中?
  • 我尝试使用-contains 使用一个循环,结果是找不到用户ID,下面是代码sn-p
  • foreach ($id in $newUsers){ if ( $id -contains $oldUsers){ Write-Host "$id Found in New user list" } else { Write-Host "$id Not Found在新用户列表中”} }
  • 看起来不错,但您只需要进行更改:$id -contains $oldUsers 应该是 $oldUsers -contains $id
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-01
  • 2023-03-21
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
相关资源
最近更新 更多