Here are two quick functions which I have recently found useful. The first tests whether a user account exists. It takes the Domain and Identity as arguments. Using the “Stop” error action with Try/Catch keeps it from showing any errors. You can do this with any of the AD cmdlets, such as Get-ADOrganizationalUnit, Get-ADComputer and others. The first example tests for the existence of a user account:
Function Test-AccountNameExists($dom, $name){ Try{ $u= get-aduser -server $dom -Identity $Name -ErrorAction Stop return $true }Catch{ return $false } }
This tests whether an OU exists:
Function Test-OUExists($dom, $OUname){ Try{$OU= Get-ADOrganizationalUnit -server $dom -Identity $OUName -ErrorAction Stop return $true }Catch{ return $false } }