Pipe to expression

Hi eevryone,

is there a way to pipe something to an expression stored in a variable, e.g.

$expression = "select -first 1"

get-process | invoke-expression $expression

 

Why?
Why not just use

Get-Process | Select -First 1

because $expression is set by user input

Okay, frankly, I would not at all recommend just taking user input and invoking it. Period. Clear avenue for exploitation, since any arbitrary code could end up being run.

That said, yes you can absolutely do this… sort of.

Option one is to specify yourself the cmdlet, but let the user set the parameters:

$input = read-host -prompt "Specify Properties"
Get-Process | Select-Object -Property $input

Option 2 will get more complex and essentially means you’ll need to wrap the string in a process { } block and then make a script block to pipe into:

$input = Read-Host 'Enter a pipeline sequence capable of handling input'
$Command = [scriptblock]::Create('process {' + $input + '}')
Get-Process | & $Command

Option 2 looks promising but isn’t working…

If you want the user to be able to change the amount of services showed you could use:

 

$x = 1
get-process | select -first $x

You can do a string building and use Invoke-Expression

$Criteria = Read-Host -Prompt "Enter the criteria" # Try Select -First 1
$FirstPart = 'Get-Process'
$FullCommand = "{0} | {1}" -f $FirstPart,$Criteria
Invoke-Expression $FullCommand
Option 2 worked like this
$Command = [scriptblock]::Create($input)
get-process | Invoke-Command $Command