我无法让此脚本按预期工作。请看下面的
我有两个数组$ 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
现在,我正在尝试编写一个脚本来检查来自$ newusers的第一个字段(Userid)是否在$ oldusers中被跟踪 然后将字段$ newusers [0],$ newusers [1],$ oldusers [2],$ newusers [2]加入$ Activeusers数组,并且在$ oldusers中找不到新的userid加入$ 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]))
}
}
}
答案 0 :(得分: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))
}
}