Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
83 lines (79 sloc) 3.15 KB
Test an Active Directory User Account
This command will test if a given Active Directory user account exists.
The name of an Active Directory user account. This should be either the samAccountName or the DistinguishedName.
Optional, a path for a log file
PS C:\> Test-ADUser rdevries
Author : Ryan DeVries
Last Updated: 2015/05/19
Version : 1
[Parameter(Position=0,Mandatory,HelpMessage="Enter an AD user name",ValueFromPipeline)]
[Parameter(Position=1,Mandatory=$false,HelpMessage="Enter the path of a log file to use")]
[ValidateScript({Test-Path (Split-Path $_ -Parent) -PathType Container})]
begin { # Configure environment, set up logging, initialize variables
if (!(Get-Module ActiveDirectory)){ Import-Module ActiveDirectory }
Write-Verbose "Starting $($MyInvocation.Mycommand)"
Write-Verbose "Detected parameter set $($PSCmdlet.ParameterSetName)"
Write-Verbose ($PSBoundParameters | out-string)
$newlog = $false
if ($log){ if(!(Test-Path $log -PathType Leaf)){ $newlog = $true } }
if ($log){
if ($newlog){
Write-Verbose "Starting log at $log"
Start-Log -Path (Split-Path $log -Parent) -Name (Split-Path $log -Leaf)
$scriptstring = "Starting $($MyInvocation.MyCommand)"
foreach ($param in $PSBoundParameters.GetEnumerator()){ $scriptstring += " -$($param.key) $($param.value)"}
Write-Log -Path $log -Line $scriptstring
process {
Write-Verbose "Searching for user $username"
if ($log){ Write-Log -Path $log -Line "Trying $username" }
# Tries to get information about the specified user, returning true if found and false if it catches the specific ADIdentityNotFound exception, terminating if it finds any other error
try {
$user = Get-ADUser -Identity $username -ErrorAction Stop
if ($log){ Write-Log -Path $log -Line "Found: $(($user | out-string).TrimEnd())`r`n" }
Write-Verbose "Found user : $(($user | out-string).TrimEnd())"
catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
if($log){ Write-Log -Path $log -Line "User $username does not exist" }
Write-Verbose "User $username does not exist"
catch {
#handle all other errors
if ($log){ Write-Log -Path $log -Line "ERROR : $($_.Exception)" }
Write-Verbose "ERROR : $($_.Exception)"
throw $_
end {
if ($log){ if($newlog) { Stop-Log -Path $log } }
Write-Verbose "Ending $($MyInvocation.Mycommand)"
Remove-Variable user -ErrorAction SilentlyContinue