Search code examples
azure-powershell

PowerShell: Using variable as scriptblock in where-object


I'm working on a script where I try to dynamically create a variable $Filter to use in Where-Object.

Obviously, this works:

$state = Get-AzPolicyState

$stateFiltered = $state | Where-Object {$_.ResourceGroup -eq "MyRG"}

However, when I use a variable, the filter doesn't work and $stateFiltered contains all records:

$Filter = "(`$_.ResourceGroup -eq `"MyRG`")"

$state = Get-AzPolicyState

$stateFiltered = $state | Where-Object {$Filter}

Any tips on why this doesn't work and how to make this work?


Solution

  • Explanation I recieved through other channel that works for me:

    In your previous code, you would generate a string, then have a scriptblock in your filter condition you have a scriptblock that just returns that string (rather than run it as code). The string is not empty, thus the condition is always true.

    The below notation will create a scriptblock from the string specified, so you can just pass it straight to the parameter, no curly braces needed in the third line (they are used to define a scriptblock, but we already have one).

    $Filter = [ScriptBlock]::Create("(`$_.ResourceGroup -eq `"MyRG`")")
    $state = Get-AzPolicyState
    $stateFiltered = $state | Where-Object $Filter