I'm trying to get a Where-Object FilterScript scriptblock into a variable, but I have had no luck far. As a simple example of what I'm trying to do:
$test = @('one','two','three')
$filter = '$_ -eq "one"'
$test | Where-Object -FilterScript { $filter }
This doesn't seem to work; I get back all elements. I've also tried:
$filter = { $_ -eq "one" }
$filter = [scriptblock]::Create($_ -eq 'one')
These all return:
one
two
three
However, replacing the variable with the actual filter works as expected:
$test | Where-Object -FilterScript { $_ -eq "one" }
This returns only "one", without "two" and "three". Does anyone know how I can make this work? I was originally trying it on Core v7.0.3, but tested on Windows PowerShell v5.1 as well.
$_
var is not defined outside of the pipeline, so your script block becomes[null] -eq 'one'
.