2013-06-27 93 views
0

我无法使该脚本按预期工作。请参考下面Powershell问题使用嵌套Foreach循环比较两个阵列

我有两个数组$ newusers使用和$ oldusers下面的数据在每个

$newusers = fadbd34|Alan Simon|Jones,ken A 
      fadbk45|Alice Lund|Dave,John h 
      fadoo78|Nathan Hugh|Trot,Carol M 
      fadt359|Jon Hart|Jones,Karen D 
      fafyl38|Miley Mcghee|Main,Josh D 
      abbrt86|Andrew Hayden|Mary,Martin G 
      frt5096|Andrew Cork|Kain,Martha E 
      ikka155|Andrew Mullen|Raymond, Gavin G 

Note: Please observe the last 3 users from $newusers are not there in $oldusers 


$oldusers = fadbd34|Alan Simon|11754 
      fadbk45|Alice Lund|11755 
      fadoo78|Nathan Hugh|11755 
      fadt359|Jon Hart|11755 
      fafyl38|Miley Mcghee|11732 

现在,我'尝试写一个脚本来检查,如果第一场(用户ID)从$ newusers使用在$ oldusers 中追踪,然后将$ newusers [0],$ newusers [1],$ oldusers [2],$ newusers [2]加入到$ Activeusers数组中,并且在$ oldusers中未找到新用户标识加入$ newusers [ 0],$ newusers [1],$ newusers [2]转换为$ Inactiveusers数组。我得到不正确的结果。以下是我能想出的。

$Activeusers = @() 
$Inactiveusers = @() 
foreach ($nrow in $newusers) { 
    foreach ($orow in $oldusers){ 
    ($idNew,$newusrname,$mgr) = $newrow.split('|') 
    ($idOld,$oldusrname,$costcntr) = $oldrow.split('|') 
     if ($idOld[0] -ieq $idOld[0]){ 
     $Activeusers += [string]::join('|',($idNew[0],$nusrname[1],$cstcntr[2],$mgr[2])) 
     } else {  
     $Inactiveusers += [string]::join('|',($idNew[0],$nusrname[1],$mgr[2])) 
    } 
    } 
} 

回答

4

问题在于你如何循环记录。您将新用户列表中的第一条记录与第二个列表中的所有用户列表进行比较。这个基本的if/else语句会导致您获得以下结果。例如:

Loop 1: compare: 
fadbd34 = fadbd34 -> Active User 
Loop 2: compare: 
fadbd34 = fadbk45 -> Inactive User 
Loop 3: compare: 
fadbd34 = fadoo78 -> Inactive User 
... 

这会导致您获得1个正确的活动用户以及5个非活动用户的列表。每当用户与旧列表中的用户不匹配时,就会将其存储为非活动用户。 (清理之后,删除不必要的数组引用(如果将字符串拆分并将其存储在变量中,则不需要数组引用),修复变量名称,以及更改if语句以比较$ idOld到$ idNew)是这样的:

$newusers = 
"fadbd34|Alan Simon|Jones,ken A", 
"fadbk45|Alice Lund|Dave,John h", 
"fadoo78|Nathan Hugh|Trot,Carol M", 
"fadt359|Jon Hart|Jones,Karen D", 
"fafyl38|Miley Mcghee|Main,Josh D", 
"abbrt86|Andrew Hayden|Mary,Martin G", 
"frt5096|Andrew Cork|Kain,Martha E", 
"ikka155|Andrew Mullen|Raymond, Gavin G" 

$oldusers = 
"fadbd34|Alan Simon|Jones,ken A", 
"fadbk45|Alice Lund|Dave,John h", 
"fadoo78|Nathan Hugh|Trot,Carol M", 
"fadt359|Jon Hart|Jones,Karen D", 
"fafyl38|Miley Mcghee|Main,Josh D", 
"abbrt86|Andrew Hayden|Mary,Martin G" 

$Activeusers = @() 
$Inactiveusers = @() 
foreach ($nrow in $newusers) { 
    $Active = $false 
    ($idNew,$newusrname,$mgr) = $nrow.split('|') 
    foreach ($orow in $oldusers){ 
     ($idOld,$oldusrname,$costcntr) = $orow.split('|') 
     if ($idNew -ieq $idOld){ 
      $Activeusers += [string]::join('|',($idNew,$nusrname,$costcntr,$mgr)) 
      $Active = $true 
     } 
    } 
    if (!$Active) 
    { 
     $Inactiveusers += [string]::join('|',($idNew,$newusrname,$mgr)) 
    } 
}