0

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

2 Answers 2

2
$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.

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Looking at this, I'm not sure why your export needs to be a CSV format. Given the information you're writing out, a simple .log file might work. You could use the add-content cmdlet within your loop.

$log = file.log
foreach ($i in $array) {
if ($i > 1) {
add-content $log '$($i) is greater than 1.'
} else {
add-content $log '$($i) is less than or equal to 1.'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.