Bookmark and Share Subscribe Bookmark and Share



How to check if a Domain User exists using PowerShell without loading AD Snap-Ins


 « »    

I was trying to run “New-SPSite” to create a Site Collection in SharePoint. I accidentally typed in the wrong username as the owner so I received an error. Upon investigation there is not a quick and simple way to see if a user exists outside of SharePoint before its added. Most recommended solutions require you to load an Active Directory Snap-In, which I think is overkill.

In this example I will use the old school NET command for DOS within PowerShell. NET USER is how I used to validate users back in the day when I wrote a lot of batch files.

# set the account to parse
$account = "service-sharepoint"

# we use this in case the account is in the DOMAIN\username format, it will strip out the DOMAIN\ for us
$username =  $account.Split("\") | select -last 1 

# we use the following old school DOS command to get the user info: "net user /domain username"
$checkuser = Start-Process NET -ArgumentList "USER /domain $username" -wait -NoNewWindow -PassThru

# store the exit code in a variable
$value = $checkuser.ExitCode

        # if the user account exists the exit code is 0, no other exit codes should matter
        if ($value -eq 0)
		Write-Host "`r`n Value: `"$value`""
		Write-Host "`r`n Success: User Account: `"$account`" exists on domain. Proceeding." -ForegroundColor Green
		# run your other code here
		Write-Host "`r`n Value: `"$value`""
		Write-Host "`r`n Error: User Account: `"$account`" could not be found. Exiting." -ForegroundColor Red

    Did I save you time and headaches? Buy me a cup of coffee.
    The more coffee I drink the more articles I can write.