10

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?

1
  • 1
    variables are not interpolated in single quote strings. Commented Aug 20, 2015 at 14:59

4 Answers 4

17

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

Sign up to request clarification or add additional context in comments.

Comments

1

Add double quote

$nameRegex = "chalmw-dm*"

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

Comments

0

Try this:

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

Comments

-1

Or

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

if you would like to use wildcards.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.