$var =@( @{id=\"1\"; name=\"abc\"; age=\"1\"; },
@{id=\"2\"; name=\"def\"; age=\"2\"; } );
$properties = @(\"ID\",\"Name\",\"Age\") ;
$format = @();
foreach (
While the whole approach seems misguided for the given example, just as an exercise in making it work the key is going to be controlling variable expansion at the right time. In your foreach
loop, $_
is null ($_
is only valid in the pipeline). You need to wait until it gets to the Foreach-Object
loop to try and evaluate it.
This seems to work with a minimum amount of refactoring:
$var =@( @{id="1"; name="abc"; age="1"; },
@{id="2"; name="def"; age="2"; } );
$properties = @("ID","Name","Age") ;
$format = @();
foreach ($p in $properties)
{
$format += @{label=$p ; Expression = [scriptblock]::create("`$`_.$p")}
}
$var | % { [PSCustomObject] $_ } | ft $format
Creating the scriptblock from an expandable string will allow $p
to expand for each property name. Escaping $_
will keep it as a literal in the string, until it's rendered as a scriptblock and then evaluated in the ForEach-Object
loop.