I have a configurable Powershell 5.1 script with the following variable:
[bool]$SourceFilter
Based on the value of this boolean, I may or may not trigger a Where-Object clause in the middle of a pipeline, which is filtering a large and complex Array of objects:
$objectArray <# | Where-Object {$_.Attributes.Value -NotLlike "*this*"} #> | Sort-Object -Property {$_.Attributes.Name}
How do I encode the Where-Object clause to only trigger if $SourceFilter = $true?
I've tried encoding the clause as a variable and then using Invoke-Expression to rationalise it into the pipeline, but can't seem to get this working:
$script = '| Where-Object {$_.Attributes.pointsource -NotLike "*AF*"}'
$output = if($SourceFilter)
{Invoke-Expression "$objectArray $script" | Sort-Object -Property {$_.Attributes.Name}}
else
{$objectArray | Sort-Object -Property {$_.Attributes.Name}}
This approach gives me an error which states that the $variable is not recognised as the name of a cmdlet, script or program.
You can have a scriptblock variable set to either your condition or true.
$sb1 = {$true}
$sb2 = {$_ -like 'a*'}
echo hi | where $sb1
hi
echo hi | where $sb2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.