Check if a useraccount exists with PowerShell

Function below can be used to check if a given Username exists in Active Directory:

function UserExists([string]$Username)
{
	$strFilter = "(&(objectCategory=person)(sAMAccountName=$Username))"

	$objDomain = New-Object System.DirectoryServices.DirectoryEntry

	$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
	$objSearcher.SearchRoot = $objDomain
	$objSearcher.PageSize = 1000
	$objSearcher.Filter = $strFilter
	$objSearcher.SearchScope = "Subtree"

	$colResults = $objSearcher.FindAll()
	return [bool]($colResults -ne $null)
}

Was once an enthusiastic PepperByte employee but is now working elsewhere. His blogs are still valuable to us and we hope to you too.