Get-ADComputer ErrorAction Problems Using Filter Parameter

Hi,

Some of our computer names are derived from the computer asset number which has worked well for us for a long time. The issue we get is when a user provides us with just the asset number. Performing any task on that computer first requires us to get the computer name.

A simple one liner will get the computer from AD as below:

Get-ADComputer -Filter 'name -like "*12345"'

In order to pass a value to it, a variable was created and used

$WCComputer = "*$Computer"

Get-ADComputer -Filter 'name -like $WCComputer'

This was part of a bigger script and was used to pass the ADComputer name through the pipeline This all works fine until an AD object is not returned, then null is passed.

For some reason when you use the filter parameter you can’t trap the fact that an object isn’t found. If I use either line below I get an error I can manage.

Get-ADComputer -Identity '*12345'
or
Get-ADComputer -Identity $WCComputer

It appears that using the Identity parameter doesn’t error. Can anyone help me get around this please ?

Any help would be much appreciated.
Thanks

Hi TonyW,

That is the expected output. It is the same with any -Filter or when using Where-Object

You can use an if/else statement to capture the result if nothing was returned.

[pre]
$WCComputer = “*$Computer”
$ComputerName = Get-ADComputer -Filter ‘name -like $WCComputer’
if (!$ComputerName {
Write-Warning ‘No computers were found using the filter provided’
}
else {
return $ComputerName
}
[/pre]

Hi pwshliquori,

Thanks for the quick reply.

I was just thinking about it some more and figured that was probably the case.

I’d never really given the -filter parm much thought as to how it works. I’m guessing now it gets all adcomputers then filters them so a result of null is not an error.

My mind had gone one down one track and I just couldn’t see my incorrect logic.

The if/else will do the job nicely.

Thanks again.