1

PowerShell 初学者在这里。到目前为止享受它!

我有一个需要与 AD 进行比较的用户列表。我创建了一个脚本来为每个用户搜索 Get-ADUser Name 和 EmailAddress,使用 Divisions 数组作为过滤器。

如果找到 AD 用户,则找到 write-host 用户,显示名称、电子邮件地址!很容易。

如果未找到 AD 使用,则继续循环遍历所有分区,直到最后一个分区,如果在任何分区中均未找到,则仅打印一次“在 AD 中未找到用户”

我一直在玩各种 Do-While、Do-Until 循环和 If-ElseIf 语句,但我无法弄清楚如果在任何部门中都没有发现它只报告一次。

$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

怎样才能做得更好?

4

1 回答 1

0

由于您的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"
}
于 2021-11-10T17:57:17.970 回答