1

我有两个数组 $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 得到一个结果。任何人都可以帮助我了解我需要在上面的代码片段中进行哪些更改吗?

4

1 回答 1

3

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

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

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。

于 2013-06-26T16:05:12.663 回答