Using "-Filter" with a variable Using "-Filter" with a variable powershell powershell

Using "-Filter" with a variable


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).


Add double quote

$nameRegex = "chalmw-dm*"

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


Try this:

$NameRegex = "chalmw-dm"  $NameR = "$($NameRegex)*"Get-ADComputer -Filter {name -like $NameR -and Enabled -eq $True}