我已经使用以下Powershell脚本工作,该脚本搜索AD用户的姓氏,并且我没有得到我预期的foreach循环输出结果。 Server 2008 R2 Domain和Powershell v3
如果我有UserA LastName1和UserB LastName1,结果输出如下:
请输入用户名:LastName1
User Name: UserB LastName1 UserA LastName1
Login Name: UserB.LastName1 UserA.LastNam1
Year Created: 2012 2014
User Name: UserB LastName1 UserA LastName1
Login Name: UserA.LastName1 UserA.LastName1
Year Created: 2012 2014
我试图像这样输出:
User Name: UserB LastName1
Login Name: UserB.LastName1
Year Created: 2012
User Name: UserA LastName1
Login Name: UserA.LastName1
Year Created: 2014
我使用的脚本如下:
$UserName = read-host "Please Enter Users LastName"
$SAN = "*$UserName*"
$GetUser = GET-ADUSER -Filter {(SamAccountName -like $SAN) -and (enabled -ne "FALSE")}
-Properties * | Sort-Object givenname -Descending
foreach ($FoundUser in $GetUser)
{
write-host "User Name: " $GetUser.CN
write-host "Login Name: " $GetUser.samaccountname
write-host "Year Created: " $getUser.whencreated.year
write-host
}
$ GetUser.CN 结果如下,所以我试图弄清楚为什么我的写主机每行产生两个条目。
UserB LastName1
UserA LastName1
答案 0 :(得分:2)
在foreach
循环中,您需要将每个$GetUser
替换为$FoundUser
。 $GetUser
包含整个列表,而$FoundUser
是当前列表条目,随着循环的每次迭代而变化。您当前实现它的方式是,每次迭代打印列表的全部内容,而不是仅打印当前项目。
您的更新代码如下所示:
$UserName = read-host "Please Enter Users LastName"
$SAN = "*$UserName*"
$GetUser = GET-ADUSER -Filter {(SamAccountName -like $SAN) -and (enabled -ne "FALSE")}
-Properties * | Sort-Object givenname -Descending
foreach ($FoundUser in $GetUser)
{
write-host "User Name: " $FoundUser.CN
write-host "Login Name: " $FoundUser.samaccountname
write-host "Year Created: " $FoundUser.whencreated.year
write-host
}