Powershell: Use a variable to reference a property of $_ in a script block
问题 $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 = {$_.$p}} #$_.$p is not working! } $var |% { [PSCustomObject]$_ } | ft $format In the above example, I want to access each object's property through a variable name. But it cannot work as expected. So in my case, how to make Expression = {$_.$p} working? 回答1: The OP's code and this answer use PSv3+