Search code examples
powershelladsi

Issues with [ADSI]::Exists


I'm trying to figure out if a user exists before I attempt to delete it. I found this command and tried to implement it into my script. I notice however, that the command will return true any username I typed into it, whether it exist or not. Can someone help explain to me the proper way of using this script, or can someone show me a better way of determining if a user exists?

[ADSI]::Exists("WinNT://Lotzi")

The following code should fail b/c Lotzi is not an actual user, but the command will return true.


Solution

  • Here's one quick way to check whether a specific account exists in Active Directory:

    $accountName = "testname"
    $searcher = [ADSISearcher] "(sAMAccountName=$accountName)"
    $accountExists = $searcher.FindOne() -ne $null