Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to test for the existence of a computer account in Active Directory with PowerShell using only tools from Microsoft.

Using Quest AD cmdlets, I can do this:

if (!(get-qadcomputer $name)){ Stuff }

That doesn't work with get-adobject or get-adcomputer as far as I can tell.

Is there something simple that I'm missing? I've seen a couple hacky-looking solutions that trap all exceptions that get thrown, but that seems like it could give some false positives under certain circumstances.

share|improve this question
$c = Get-ADComputer <$ComputerName>
if($c -eq $null) { ItDoesntExist } else { ItLives }

This should do exactly what you need... you said it isn't working for you, why exactly?

Sorry, looks like this cmdlet actually throws an exception instead of simply returning $null, as documented here... and it also ignores the -erroraction parameter (scroll down to the comments on the linked page).

Suggested workaround:

$errorActionPreference = "SilentlyContinue"

Get-ADComputer <$ComputerName>

Or, better, see my other answer.

share|improve this answer
I get Get-ADComputer : Cannot find an object with identity: 'test' under: 'DC=my,DC=domain'. At line:1 char:20 + $c = Get-ADComputer <<<< "test" + CategoryInfo : ObjectNotFound: (test:ADComputer) [Get-ADComputer], ADIdentityNotFoundException + FullyQualifiedErrorId : Cannot find an object with identity: 'test' under: 'DC=my,DC=domain'.,Microsoft.ActiveDirectory.Ma nagement.Commands.GetADComputer when running it against a machine that doesn't exist. – MDMarra Sep 14 '11 at 17:55
Maybe do something with -erroraction? Suppress the error and test for it? – Zoredache Sep 14 '11 at 18:23
Ops. Looks like it's a known (and frustrating) issue:… (scroll down to the comments). – Massimo Sep 14 '11 at 18:28
Yeah, not returning $null like a good cmdlet is what's been killing me. I'm trying out your other answer now, though. – MDMarra Sep 14 '11 at 18:40

Try to delete it and read the return code for that?

(Just kidding. Kind of.)

share|improve this answer

To test an AD Object in general by DistinguishedName, you can use the following:

[bool](Get-ADObject -Filter {DistinguishedName-eq "CN=Users,DC=domain,DC=local"})

Or, when you want to search by another property like samaccountname:

[bool](Get-ADObject -Filter {sAMAccountname -eq "Administrator"})

Both will return only a boolean ($true or $false) and can be used in conditional logic (if/else, etc).

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.