简体   繁体   中英

Powershell Nested Foreach loop giving incorrect results

i have two arrays $newUsers and $oldUsers already populated with userid's in the script i've written. My next goal is to check whether the userid from $newUsers exists in $oldUsers. if yes, then display statement Write-Host "New User_id $rowNew found in Old user list" else display Write-Host "New User_id $rowNew Notfound in Old user list"

below is the logic i used and the output i'am getting.

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

--Result

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

Not sure why i'am getting the above results, should'nt i be getting one result for each userid. could anyone help me as to what i need to change in code snippet above?

I think the problem is that you are trying to match every item in one file to every other item in the other file so each run of the outer loop wil result in one possible and lots of non matches.

Why not use the Compare-Object instead like so:

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

Another alternative would be to just do one loop and use -contains instead of -ieq.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM