PowerShell初学者。到目前为止很享受!
我有一个需要与AD进行比较的用户列表。我创建了一个脚本,使用Divisions数组作为过滤器,为每个用户搜索Get-ADUser Name和EmailAddress。
如果找到AD用户,则写入找到的主机用户,显示名称、电子邮件地址!很简单。
如果未找到AD使用,则在所有"分段"中保持循环,直到最后一个分段为止,如果在任何"分段"内未找到,则只打印一次";在AD中找不到用户";
我一直在玩各种Do While、Do Until循环和If ElseIf语句,但如果在任何分区中都找不到,我无法使其只报告ONCE。
$Divisions="1","2","3"
$lastd = $Divisions | Select-Object -Last 1
Foreach ($d in $Divisions){
$aduser = Get-ADUser -Filter "Surname -like '*$lastname' -and GivenName -like '$givenname*'`
-and Enabled -eq '$True' -and Division -eq '$d'"`
-SearchBase "OU" -Properties Name, Division, EmailAddress |Select-Object Name,Division,EmailAddress
if(!$aduser){
write-host "Usernotfound"
}
if($aduser -eq ""){
write-host "user not found in AD" `n
}
else{
write-host "User Found in $d :" $aduser.Name $aduser.EmailAddress -F Green `n
}
}
以下是运行脚本时的示例结果。
USER1 - account will be terminated in 35 days; Last signon activity 2 days ago
****Searching: Active Directory Information
Usernotfound
Usernotfound
Usernotfound
Usernotfound
Usernotfound
Usernotfound
User Found in Division1! Name EmailAddress
USER2 - account will be terminated in 43 days; Last signon activity 4 days ago
****Searching: Active Directory Information
Usernotfound
Usernotfound
Usernotfound
Usernotfound
Usernotfound
Usernotfound
User Found in Division2! Name EmailAddress
Usernotfound
Usernotfound
Usernotfound
如何才能做得更好?
由于您的foreach
循环似乎只属于单个用户(同时在多个分区中反复查找该用户(,因此您可以简单地将未找到的测试移动到循环后的:
foreach ($d in $Divisions) {
$aduser =
Get-ADUser -Filter "Surname -like '*$lastname' -and GivenName -like '$givenname*' -and Enabled -eq 'True' -and Division -eq '$d'" -Properties Name, Division, EmailAddress |
Select-Object Name,Division,EmailAddress
if ($adUser) {
Write-Host "User Found in $d :" $aduser.Name $aduser.EmailAddress -F Green `n
break # Presumably you needn't keep searching.
}
}
if (-not $aduser) {
Write-Host "Usernotfound"
}