Your options are:
- 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
- A
filter
, exactly the same functionality:
filter thing {
switch ($_) {
1 { "one." }
2 { "two." }
3 { "three." }
}
}
1..3 | thing
- 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))
- 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)) }
- 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 } }