Get-AdUser <username> error checking RRS feed

  • Question

  • Hi all,

    I have a script that reads from a CSV and then uses one of the fields to match the username in AD (SamAccountName property).  I need to do some error checking though to stop the script if the user doesn't exist.  

    I came up with the following but of course the error fails on the first command.

    $UserProperties = Get-ADUser $_.Username -Properties *
    If (!($UserProperties.SamAccountName -eq $Null)) {
    Do Stuff

    Can anyone suggest the best way to go about checking the username in the CSV is a valid username?

    Many thanks!

    Wednesday, December 4, 2013 2:12 PM


  • Hi,

    This will notify you if a username is invalid and then continue to process the next user in the list:

    $badUsers = @()
    Import-Csv .\users.csv | ForEach {
        $user = $_.UserName
        try {
            $userProps = Get-ADUser $user -Properties *
            $userProps | Select Name,SamAccountName
        catch {
            Write-Host "$user is invalid" -BackgroundColor Black -ForegroundColor Red
            $badUsers += $user
    Write-Host "`nList of invalid usernames:"

    Don't retire TechNet! - (Don't give up yet - 12,420+ strong and growing)

    • Marked as answer by AJPalmer Wednesday, December 4, 2013 4:01 PM
    Wednesday, December 4, 2013 2:25 PM

All replies