Help with error handling output to file for Get-ADUser

Beto Sanchez 21 Reputation points

The below works for me but I need to figure out how to get the output file to have the EMPID listed as bad if it is not found. These lists are sometimes created manually so I need to find out what line or the currently listed EMPID that is not found. Currently the script runs and gets me the information I need but it doesn't tell me if any of the EMPIDs were not found. I only know there is an issue because the output comes out a line or 2 short of what I expected.


Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,416 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 31,341 Reputation points Microsoft Vendor


    Please don't post your code as an image. You just need to test if the AD user exists

    Import-Csv C:\Temp\EMPID.csv | ForEach-Object {  
        $user = Get-ADUser -Filter "EmployeeID -eq $($_.EmployeeID)"   
        $user | Select-Object Name, SamAccountName, UserPrincipalName          
        if(-not $user){  
            $_ |Export-Csv C:\temp\EmpIDnotfound.csv -Encoding UTF8 -NoTypeInformation -Append  
    } | Export-Csv C:\temp\EmpIDresults.csv -Encoding UTF8 -NoTypeInformation  

    Best Regards,
    Ian Xue


    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 45,186 Reputation points

    How about something like this?

    Import-CSV C:\temp\empids.csv |
            $x = Get-ADUser -Filter "EmployeeID -eq $($_.EmployeeID)"
            if ($x){
                $x | Select-Object sAMAccountName, UserPrincipalName, EmployeeID
                    sAMAccountName = "NotFound"
                    UserPrincipalName = "NotFound"
                    EmployeeID = $_.EmployeeID
        } | Export-CSV . . .