2013-06-26 61 views
1

我有两个数组$ newUsers和$ oldUsers已经在我写的脚本中填充了userid's。我的下一个目标是检查$ newUsers中是否存在$ newUsers的用户标识。如果是,则显示语句Write-Host“New User_id $ rowNew in old user list”else else显示Write-Host“New User_id $ rowNew Not Found in Old user list”PowerShell嵌套Foreach循环给出不正确的结果

以下是我使用的逻辑和输出i '越来越。

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 

不知道为什么我'得到上述结果,should'nt我越来越对每个用户ID一个结果。任何人都可以帮助我,我需要改变上面的代码片段?

+1

我建议使用'compare-object' cmdlet。 –

回答

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" 
} 

另一种办法是只是一个循环,而是使用-ieq的-contains。

+0

谢谢戴夫!它的工作,进一步分析我的脚本中的这些userid的我将如何通过分配找到的userid到一个数组中,而不是在foreach-object循环中发现到另一个数组中? – user1411254

+0

我尝试使用一个循环通过使用-contains和结果出来没有userid的发现,下面是代码片段 – user1411254

+0

foreach($ newUsers中的$ id){ if($ id -contains $ oldUsers){ Write-Host “$ id在新用户列表中找到” } else { Write-Host“$ id Not found in New user list” } } – user1411254