2

I have a variable that stores a switch statement

$com = '
switch ($_)
{
    1 {"It is one."}
    2 {"It is two."}
    3 {"It is three."}
    4 {"It is four."}
}
'

I am trying to pipe in the number to run the switch statement

something like:

1 | iex($com)

Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37
I am Jakoby
  • 577
  • 4
  • 19

1 Answers1

3

Your options are:

  1. A scriptblock or function with a process block:
$com = {
    process {
        switch ($_) {
            1 { "one."   }
            2 { "two."   }
            3 { "three." }
        }
    }
}

function thing {
    process {
        switch ($_) {
            1 { "one."   }
            2 { "two."   }
            3 { "three." }
        }
    }
}

1..3 | & $com
1..3 | thing
  1. A filter, exactly the same functionality:
filter thing {
    switch ($_) {
        1 { "one."   }
        2 { "two."   }
        3 { "three." }
    }
}

1..3 | thing
  1. Using ScriptBlock.Create method (this would require a process block in the string expression):
$com = '
process {
    switch ($_) {
        1 { "one."   }
        2 { "two."   }
        3 { "three." }
    }
}
'

1..3 | & ([scriptblock]::Create($com))
  1. Using ScriptBlock.InvokeWithContext method and the automatic variable $input, this technique does not stream and also requires an outer scriptblock to work, it's just to showcase and should be discarded as an option:
$com = '
switch ($_) {
    1 { "one."   }
    2 { "two."   }
    3 { "three." }
}
'

1..3 | & { [scriptblock]::Create($com).InvokeWithContext($null, [psvariable]::new('_', $input)) }
  1. Using Invoke-Expression, also requires an outer scriptblock with a process block (should be discarded - from all techniques displayed above this is the worst one, the string expression is being evaluated per item passed through the pipeline):
$com = '
switch ($_) {
    1 { "one."   }
    2 { "two."   }
    3 { "three." }
}
'

1..3 | & { process { Invoke-Expression $com } }
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37