Using "-Filter" with a variable

I am trying to filter out something like this:

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

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

Now I want the "name-like ..." part to be such a variable:

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

I checked a few questions (e.g. ADS PowerShell Module - Variables in a Filter ), but this does not work for me.

I tried this with the following:

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

And also in the Get-ADComputer with these and without.

Can someone give me some advice?

+7
source share
3 answers

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

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

in it:

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

Please note, however, that the script 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 to this . Also related .

And FTR: here you are using a wildcard (operator -like ), not regular expressions (operator -match ).

+9
source

Add double quotation mark

 $nameRegex = "chalmw-dm*" 

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

+1
source

or

 -like '*'+$nameregex+'*' 

if you want to use wildcards.

0
source

Source: https://habr.com/ru/post/1202954/


All Articles