$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?
The OP's code and this answer use PSv3+ syntax. Casting a hashtable to
[pscustomobject]
is not supported in PSv2, but you can replace[pscustomobject] $_
withNew-Object PSCustomObject -Property $_
.As in many cases in the past, PetSerAl has provided the answer in terse (but very helpful) comments on the question; let me elaborate:
Your problem is not that you're using a variable (
$p
) to access a property per se, which does work (e.g.,$p = 'Year'; Get-Date | % { $_.$p }
).Instead, the problem is that
$p
in script block{ $_.$p }
isn't evaluated until later, in the context of theFormat-Table
call, which means that the same, fixed value is used for all input objects - namely the value of$p
at that point (which happens to be the last value that was assigned to$p
in theforeach
loop).The cleanest and most generic solution is to call
.GetNewClosure()
on the script block to bind$p
in the script block to the then-current, loop-iteration-specific value.From the docs (emphasis added):
Note that automatic variable
$_
is undefined inside theforeach
loop (PowerShell defines it only in certain contexts as the input object at hand, such as in script blocks passed to cmdlets in a pipeline), so it remains unbound, as desired.Caveats:
While
.GetNewClosure()
as used above is convenient, it has the inefficiency drawback of invariably capturing all local variables, not just the one(s) needed.A more efficient alternative that avoids this problem - and notably also avoids a bug (as of Windows PowerShell v5.1.14393.693 and PowerShell Core v6.0.0-alpha.15) in which the closure over the local variables can break, namely when the enclosing script / function has a parameter with validation attributes such as
[ValidateNotNull()]
and that parameter is not bound (no value is passed)[1] - is the following, significantly more complex expression Tip of the hat again to PetSerAl, and Burt_Harris's answer here :& { ... }
creates a child scope with its own local variables.$p = $p
then creates a local$p
variable from its inherited value.To generalize this approach, you must include such a statement for each variable referenced in the script block.
{ $_.$p }.GetNewClosure()
then outputs a script block that closes over the child scope's local variables (just$p
in this case).For simple cases, mjolinor's answer may do: it indirectly creates a script block via an expanded string that incorporates the then-current
$p
value literally, but note that the approach is tricky to generalize, because just stringifying a variable value doesn't generally guarantee that it works as part of PowerShell source code (which the expanded string must evaluate to in order to be converted to a script block).To put it all together:
This yields:
as desired: the output columns use the column labels specified in
$properties
while containing the correct values.Note how I've removed unnecessary
;
instances and replaced built-in aliases%
andft
with the underlying cmdlet names for clarity. I've also assigned distinctage
values to better demonstrate that the output is correct.Simpler solution, in this specific case:
To reference a property value as-is, without transformation, it is sufficient to use the name of the property as the
Expression
entry in the calculated property (column-formatting hashtable). In other words: you do not need a[scriptblock]
instance containing an expression in this case ({ ... }
), only a[string]
value containing the property name.Therefore, the following would have worked too:
Note that this approach happens to avoid the original problem, because
$p
is evaluated at the time of assignment, so the loop-iteration-specific values are captured.[1] To reproduce:
function foo { param([ValidateNotNull()] $bar) {}.GetNewClosure() }; foo
fails when.GetNewClosure()
is called, with errorException calling "GetNewClosure" with "0" argument(s): "The attribute cannot be added because variable bar with value would no longer be valid."
That is, an attempt is made to include the unbound
-bar
parameter value - the$bar
variable - in the closure, which apparently then defaults to$null
, which violates its validation attribute.Passing a valid
-bar
value makes the problem go away; e.g.,foo -bar ''
.The rationale for considering this a bug: If the function itself treats
$bar
in the absence of a-bar
parameter value as nonexistent, so should.GetNewClosure()
.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 theForeach-Object
loop to try and evaluate it.This seems to work with a minimum amount of refactoring:
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 theForEach-Object
loop.Accessing anything inside an Array of HashTables is going to be a bit finicky, but your variable expansion is corrected like this:
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.