Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select-Object Expression as a string

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?

like image 913
runaboutfence Avatar asked Jun 18 '26 15:06

runaboutfence


2 Answers

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

Edit

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).

like image 138
briantist Avatar answered Jun 21 '26 20:06

briantist


You're looking for Invoke-Expression:

$csvdata | select-object (Invoke-Expression $tstexp)
like image 37
Jeroen Mostert Avatar answered Jun 21 '26 20:06

Jeroen Mostert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!