If I type out my Powershell select-object expression like below:
$csvdata | Select-Object @{expression={$_.1}; label='first'}
I receive desired output:
first
-
mike
john
But if I store the expression as a string first and then call that string as the expression to select-object:
$tstexp = "@{expression={`$_.1}; label='first'}"
$csvdata | Select-Object $tstexp
The output doesn't evaluate correctly and is used instead as the object name.
@{expression={$_.1}; label='first'}
-------------------------------
Is it possible to pass select-object an expression list as a string?
You can pass it as a [Hashtable]:
$tstexp = @{expression={$_.1}; label='first'}
$csvdata | Select-Object $tstexp
(just remove the quotes).
If it must be a string (I can only imagine that you are reading/generating it from outside your script), then you could evaluate it as a script block:
# Create the string
$tstexp = "@{expression={$_.1}; label='first'}"
# Convert to script block
$tstblock = [scriptblock]::Create($tstexp)
# Execute script block
$tstval = & $tstblock
# $tstval now contains the hashtable
$csvdata | Select-Object $tstval
If you must use a string, it's easier to use Invoke-Expression as Jeroen Mostert's answer explains (but of course, avoid the string if possible).
You're looking for Invoke-Expression:
$csvdata | select-object (Invoke-Expression $tstexp)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With