首页 > 解决方案 > Powershell 脚本检查用户是否存在于 Active Directory 中并导出到 csv

问题描述

我有一个现有的脚本,它可以检查给定用户是否存在于 AD 中。但我无法将结果导出到 csv 文件中。请帮忙。

Clear-Host
$UserList = gc .\Output_userInfo.csv
$outputFilePath = "D:\Input\User&Group_Output.csv"
foreach ($u in $UserList) {
    try {
        $ADUser = Get-ADUser -Identity $u -ErrorAction Stop 
    }
    catch { 
        if ($_ -like "Cannot find an object with identity: '$u'") { 
            "User '$u' does not exist." | Export-Csv .\notexists.csv -NoTypeInformation -Force 
        }
        else { 
            "An error occurred: $_" 
        } continue 
    } 
    "User '$($ADUser.SamAccountName)' exists." | 
    Export-Csv .\notexists.csv -NoTypeInformation -Force 
}

标签: powershell

解决方案


$UserList = gc C:\temp\Output_userInfo.csv #use full path instead. .\ is relative path and could cause issues if you are not careful
$outputFilePath = "D:\Input\User&Group_Output.csv"

$finalResult = foreach ($u in $UserList)
{
    #CSV takes data in a table format. So best to replicate that with a PS Cusotm object that can easily be represented ina table format.
    $obj = [PSCustomObject]@{
        UserName = $u
        Status = ""
    }
    try
    {
        $ADUser = Get-ADUser -Identity $u -ErrorAction Stop
        $obj.Status = "Exists"
    }
    catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
    {
        $obj.Status = "Does not Exist"
    }
    catch
    {
        $obj.Status = $_.Exception.Message
    }
    $obj
}

$finalResult | Export-Csv -Path $outputFilePath -NoTypeInformation -Force

如果您想知道我是如何知道第一次捕获中使用的错误类型的,您可以通过模拟错误来找到它[在这种情况下,get-aduser blah由于这样的用户不存在,所以会这样做]。然后您可以如图所示展开最后一条错误消息select *并查看异常类型。或者,您也可以尝试阅读文档,但我没有那种耐心。

在此处输入图像描述


推荐阅读