Powershell: Use a variable to reference a property of $_ in a script block

前端 未结 3 889
我在风中等你
我在风中等你 2021-02-06 16:46
$var =@(  @{id=\"1\"; name=\"abc\"; age=\"1\"; },
          @{id=\"2\"; name=\"def\"; age=\"2\"; } );
$properties = @(\"ID\",\"Name\",\"Age\") ;
$format = @();
foreach (         


        
3条回答
  •  情歌与酒
    2021-02-06 17:34

    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.

提交回复
热议问题