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

前端 未结 3 890
我在风中等你
我在风中等你 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:14

    Accessing anything inside an Array of HashTables is going to be a bit finicky, but your variable expansion is corrected like this:

        $var =@(  @{id="1"; name="Sally"; age="11"; },
              @{id="2"; name="George"; age="12"; } );
    $properties = "ID","Name","Age"
    $format = @();
    
    $Var | ForEach-Object{
        foreach ($p  in $properties){
            $format += @{
                $p = $($_.($p))
            }
        }
    }
    

    You needed another loop to be able to tie it to a specific item in your array. That being said, I think that going with an array of Objects would be a much cleaner approach - but I don't know what you're dealing with, exactly.

提交回复
热议问题