Our Man in Bananas
Our Man in Bananas

Reputation: 5979

evalute expression output into variable in PowerShell

I want to be able to build a Get-ADComputer command after building it from strings like so:

$FilterOperatingSystems = "*Windows 7*" -or OperatingSystem -like "*Windows 8*" -or OperatingSystem -like "*Windows 10*"

($FilterOperatingSystems is a parameter to the script, so it'll be future proofed when executed by a Task Scheduler)

$command='Get-ADComputer -properties OperatingSystem -Filter {(OperatingSystem -like '+$FilterOperatingSystems+' )} |'
$command+= 'Where-Object {$_.name -like "*-*"} | '
$command+= 'Where-Object {$_.name -NotLike "V7-*"} | '
$command+= 'Where-Object {$_.name -NotLike "*-NONE"} | '
$command+= 'Where-Object {$_.name -NotLike "*-ONCALL"} | '
$command+= 'Where-Object {$_.name -NotLike "*-BLACKBAUD"} | '
$command+= 'Where-Object {$|_.name -NotLike "SC-WIN7-1"} | '
$command+= 'Where-Object {$_.name -NotLike "UT-SWCLIENT-01"} | '
$command+= 'Select-Object -Expand Name'

Write-Host $command

$computer =iex $command 

the $command comes out like this:

Get-ADComputer -properties OperatingSystem -Filter {(OperatingSystem -like "*Windows 7*" -or OperatingSystem -like "*Windows 8*"  -or OperatingSystem
 -like "*Windows 10*"  )} |Where-Object {$_.name -like "*-*"} | Where-Object {$_.name -NotLike "V7-*"} | Where-Object {$_.name -NotLike "*-NONE"} | W
here-Object {$_.name -NotLike "*-ONCALL"} | Where-Object {$_.name -NotLike "*-BLACKBAUD"} | Where-Object {$|_.name -NotLike "SC-WIN7-1"} | Where-Obje
ct {$_.name -NotLike "UT-SWCLIENT-01"} | Select-Object -Expand Name

but I get an error:

$ : The term '$' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

So, is it possible to do something like that? And if so, what's the right approach?

Upvotes: 0

Views: 42

Answers (1)

Gabriel Luci
Gabriel Luci

Reputation: 40998

I think you just have a typo:

$|_.name -NotLike "SC-WIN7-1"

Should that not be $_.name?

Upvotes: 2

Related Questions