写一个 catch 来显示不在 AD 中的用户名

Write a catch to display usernames that are not in AD

我想写一行,让我知道任何无法找到的用户名,以及它们在脚本提取的 .txt 文档中的显示名称。

基本上我只是想在现有脚本中添加一行。

任何有关如何这样做的提示或指导都将非常有用。

Get-Content C:\Users\User\Desktop\findusername.txt | Foreach-Object {get-aduser -filter "displayName -like '$($_)'" | Select-Object SamAccountName} | Export-Csv -Path C:\Users\User\Documents\ADGroupusernames.csv -NoTypeInformation

正如 Santiago 指出的那样,过滤器在找不到匹配对象时不会抛出错误。您可以改为检查是否返回任何对象并对此做出反应。

Get-Content C:\Users\User\Desktop\findusername.txt | 
    ForEach-Object { 
        if ($found = Get-ADUser -Filter "displayName -like '$($_)'") {
            $found | Select-Object SamAccountName
        }
        else {
            [PSCustomObject]@{
                SamAccountName = "Did not find '$_'"
            }
        } 
    } | Export-Csv -Path C:\Users\User\Documents\ADGroupusernames.csv -NoTypeInformation