Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "-Filter" with a variable

I try to filter out something like this:

Get-ADComputer -Filter {name -like "chalmw-dm*" -and Enabled -eq "true"} ...

This works like a charm and gets exactly what I want...

Now I want the "name -like ..." part as a variable like this:

Get-ADComputer -Filter {name -like '$nameregex' -and Enabled -eq "true"} |

I checked several questions (for example, PowerShell AD Module - Variables in Filter), but this isn't working for me.

I tried it with the following:

$nameRegex = "chalmw-dm*"
$nameRegex = "`"chalmw-dm*`""

And also in the Get-ADComputer command with those ' and without.

Could anyone give me some hints?

like image 422
Michael Avatar asked Sep 19 '14 09:09

Michael


People also ask

Can filter () execute the function for array elements without values?

The filter() method does not execute the function for empty elements.

Can you use filter on a string?

You can't use filter() on a string as it is an Array.

Does filter manipulate the array?

filter() does not modify the original array.


2 Answers

You don't need quotes around the variable, so simply change this:

Get-ADComputer -Filter {name -like '$nameregex' -and Enabled -eq "true"}

into this:

Get-ADComputer -Filter {name -like $nameregex -and Enabled -eq "true"}

Note, however, that the scriptblock notation for filter statements is misleading, because the statement is actually a string, so it's better to write it as such:

Get-ADComputer -Filter "name -like '$nameregex' -and Enabled -eq 'true'"

Related. Also related.

And FTR: you're using wildcard matching here (operator -like), not regular expressions (operator -match).

like image 145
Ansgar Wiechers Avatar answered Oct 21 '22 15:10

Ansgar Wiechers


Add double quote

$nameRegex = "chalmw-dm*"

-like "$nameregex" or -like "'$nameregex'"

like image 31
walid toumi Avatar answered Oct 21 '22 16:10

walid toumi