Using a variable with Get-ADComputer -filter

107 Views Asked by At

I might be overthinking this, but have been unable to get this simple code edit to work with Powershell

This works fine

Get-ADComputer -Filter "operatingsystem -like "Windows server 2012"

However, i'd like to use a variable such as $ServerOS = "Windows server 2022"

And then using that variable inside the same code, such as this

Get-ADComputer -Filter "operatingsystem -like "$EOLOS"

However, as the -filter uses 'single' quotes, it doesn't work. How would I edit the code to make the variable work?

Get-ADComputer -Filter "operatingsystem -like "Windows server 2012"
1

There are 1 best solutions below

0
Elior Machlev On

What I did is to split the filter parameter, insert it into a variable and call the entire variable as the filter.

With your example you will get the following result:

$EOLOS='Windows server 2012'
$Filter='operatingsystem -like "*' + $EOLOS + '*"'
#Filter value: operatingsystem -like "*Windows server 2012*"
Get-ADComputer -Filter $Filter

However, in your case specificlly, it sounds like it is best to use equal (-eq) as it is an exact value (but it is yours to decide):

$EOLOS='Windows server 2012'
$Filter='operatingsystem -EQ "' + $EOLOS + '"'
#Filter value: operatingsystem -EQ "Windows server 2012"
Get-ADComputer -Filter $Filter