Following from my comment, short answer was to use the Subexpression operator $( )
, which would allow PowerShell to reference the property $col
of the object $row
.
Short extract from MS Docs:
Use this when you want to use an expression within another expression. For example, to embed the results of command in a string expression.
To give you a short explanation of why this is needed, using this as an example:
$object = [pscustomobject]@{
foo = 'var'
}
$property = 'foo'
When we do "$object.$property"
or in simple terms, "$object.foo"
, the double quotes "..."
are not allowing PowerShell to reference the foo
property from $object
because the dot .
is interpreted as literal and not as a dot method. In addition, the quotes are converting $object
to its stringified ? representation @{foo=var}
followed by the literal dot .
followed by the variable expansion of $property
.
Another extract from about_Properties:
The most common way to get the values of the properties of an object is to use the dot method. Type a reference to the object, such as a variable that contains the object, or a command that gets the object. Then, type a dot (.) followed by the property name.
Lastly, what other alternatives do we have to get around this besides $(...)
:
'Value of $object.$property is "{0}".' -f $object.$property
[string]::Format('Value of $object.$property is "{0}".', $object.$property)
- Using
+
to concatenate strings is also a very known one:
'Value of $object.$property is "' + $object.$property + '".'
As a side note, and unrelated to the actual issue, this might be a more direct way of approaching your code:
@'
roles,admin,accountant,security
Engineer,,x,,
Operator,,y,,
'@ |
ConvertFrom-Csv | ForEach-Object -Begin { $i = 1 } -Process {
foreach($Property in $_.PSObject.Properties.Name)
{
'Value of Row {0} Column "{1}" is "{2}"' -f
$i, $Property, (
'NULL', ($val = $_.$Property)
)[[int][bool]$val]
}
$i++
}
Note the use of .PSObject
to access the object's properties and methods, an alternative to Get-Member
.
The above would result in:
Value of Row 1 Column "roles" is "Engineer"
Value of Row 1 Column "admin" is "NULL"
Value of Row 1 Column "accountant" is "x"
Value of Row 1 Column "security" is "NULL"
Value of Row 2 Column "roles" is "Operator"
Value of Row 2 Column "admin" is "NULL"
Value of Row 2 Column "accountant" is "y"
Value of Row 2 Column "security" is "NULL"