Pipe to expression

Welcome Forums General PowerShell Q&A Pipe to expression

This topic contains 7 replies, has 5 voices, and was last updated by

1 month, 2 weeks ago.

  • Author
  • #118726

    Points: 38
    Rank: Member

    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


  • #118734

    Points: 123
    Rank: Participant

    Why not just use

    Get-Process | Select -First 1
    • #118737

      Points: 38
      Rank: Member

      because $expression is set by user input

  • #118740

    Points: 290
    Helping Hand
    Rank: Contributor

    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
  • #118798

    Points: 38
    Rank: Member

    Option 2 looks promising but isn't working...

  • #118809

    Points: 870
    Helping Hand
    Rank: Major Contributor

    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
  • #118807

    Points: 26
    Rank: Member

    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

  • #118828

    Points: 38
    Rank: Member
    Option 2 worked like this
    $Command = [scriptblock]::Create($input)
    get-process | Invoke-Command $Command

You must be logged in to reply to this topic.