runaboutfence
runaboutfence

Reputation: 120

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?

Upvotes: 2

Views: 4218

Answers (2)

briantist
briantist

Reputation: 47862

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

Upvotes: 7

Jeroen Mostert
Jeroen Mostert

Reputation: 28809

You're looking for Invoke-Expression:

$csvdata | select-object (Invoke-Expression $tstexp)

Upvotes: 3

Related Questions