Test for existence of an AD object in PowerShell using only Microsoft-provided cmdlets
Solution 1
Have a look at this:
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.
Related videos on Youtube
MDMarra
Updated on September 18, 2022Comments
-
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
orget-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 over 12 yearsI 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 over 12 yearsMaybe do something with
-erroraction
? Suppress the error and test for it? -
Massimo over 12 yearsOps. Looks like it's a known (and frustrating) issue: blogs.technet.com/b/askds/archive/2010/02/04/… (scroll down to the comments).
-
MDMarra over 12 yearsYeah, not returning $null like a good cmdlet is what's been killing me. I'm trying out your other answer now, though.
-
Avi Pars about 5 yearsWould this work with Get-ADComputer?
-
Johan de Haan about 5 yearsThis 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.