简体   繁体   中英

Powershell script check if user exists in Active Directory and export to csv

I have an existing script which does the job of checking if a given user exists in AD or not. But I'm unable to export the result in csv file. Please help.

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 
}
$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

If you are wondering how I knew the error type used in the 1st catch, you can find it by simulating an error [in this case, get-aduser blah would do it since such a user does not exist]. Then you can expand the last error message with select * as shown and look at the exception type. Alternately, you could also try to read the documentation but I don't have that kind of patience.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM