Help with error handling output to file for Get-ADUser

Beto Sanchez 21 Reputation points
2021-02-03T01:55:37.68+00:00

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.

63234-image.png

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,463 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 34,271 Reputation points Microsoft Vendor
    2021-02-03T06:29:49.037+00:00

    Hi,

    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,906 Reputation points
    2021-02-03T02:44:57.347+00:00

    How about something like this?

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