jhorsman
9/11/2017 - 2:56 PM

Test if user exists

Test if user exists

# given we have $username and a $password
if($username.Contains("\"))
{
    # system account is a domain user

    # careful here, if the user running this script is a local user this test will fail

    $rawUsername = $username.Split("\")[1]
    if(-NOT(Test-ADCredential -username $rawUsername -password $password)){
        Write-Error("The AD system account for '"+$username+"' does not exist, or the password is not correct. Please correct the credentials and rerun the script")
        exit
    }
} else
{
    # system account is a local user

    $winfilter = "LocalAccount='true' and Name='"+$username+"'"
    $serviceUser = Get-WmiObject Win32_UserAccount -Filter $winfilter
    if($serviceUser -eq $Null -or $serviceUser -eq '')
    {
        Write-Error("The local system account for '"+$username+"' does not exist, or the password is not correct. Please correct the credentials and rerun the script")
        exit
    }
}