IanB
IanB

Reputation: 271

PowerShell - Use a string in a foreach-object against the Description AD property of a computer object

I am trying to send a user name (SamAccountName) down the PowerShell Pipeline to find a computer based on the Description property in Active Directory:

The Description property is always "something-UserName"

I know I don't need to send the variable down the pipeline and can simply express it in the filter but I have s specific use case where I need to do this.

This is what I have tried:

"bloggsJ" | %{Get-ADComputer -server domain.com -Filter * -Properties Description | ?{$_.Description -eq "something-$_"}} | select Name 

This produces nothing even though there is a computer with a description property of "Something-bloggsJ" on that domain.

Any advice please.

Upvotes: 0

Views: 236

Answers (2)

Theo
Theo

Reputation: 61028

Instead of using the -eq operator, I would use -like.

Something like this:

"bloggsJ", "IanB" | ForEach-Object {
    $name = $_
    Get-ADComputer -Filter * -Properties Description | 
    Where-Object {$_.Description -like "*-$name"}
} | Select-Object Name

Inside the ForEach-Object loop, the $_ automatic variable is one of the usernames. Inside the Where-Object clause, this $_ variable represents one ADComputer object, so in order to have the username to create the -like string, you need to capture that name before entering the Where-Object clause.

Upvotes: 3

Ivan Mirchev
Ivan Mirchev

Reputation: 839

I believe you are missing the underscore for $_ variable:

"ivan" | ForEach-Object -Process { Get-ADComputer -Filter * -properties description | Where-Object -Property description -eq "something-$_"}

this one is working ...

Upvotes: 1

Related Questions