Test for existence of an AD object in PowerShell using only Microsoft-provided cmdlets

15,870

Solution 1

Have a look at this:

http://blogs.msdn.com/b/adpowershell/archive/2009/05/05/how-to-create-a-function-to-validate-the-existence-of-an-ad-object-test-xadobject.aspx

Solution 2

$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:
15,870

Related videos on Youtube

MDMarra
Author by

MDMarra

Updated on September 18, 2022

Comments

  • MDMarra
    MDMarra over 1 year

    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.

  • MDMarra
    MDMarra over 12 years
    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.
  • Zoredache
    Zoredache over 12 years
    Maybe do something with -erroraction? Suppress the error and test for it?
  • Massimo
    Massimo over 12 years
    Ops. Looks like it's a known (and frustrating) issue: blogs.technet.com/b/askds/archive/2010/02/04/… (scroll down to the comments).
  • MDMarra
    MDMarra over 12 years
    Yeah, not returning $null like a good cmdlet is what's been killing me. I'm trying out your other answer now, though.
  • Avi Pars
    Avi Pars about 5 years
    Would this work with Get-ADComputer?
  • Johan de Haan
    Johan de Haan about 5 years
    This works with a lot of cmdlets which return an object or not. If it returns an object (or more) and you cast it to type boolean it will become a true, without an object returned it will become a false.