我有一个变量来存储一个开关语句
$com = '
switch ($_)
{
1 {"It is one."}
2 {"It is two."}
3 {"It is three."}
4 {"It is four."}
}
'
我正在尝试输入数字以运行开关语句。
类似于:
1 | iex($com)
发布于 2022-11-30 18:52:13
你的选择是:
$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
functionality:
filter
,完全相同filter thing {
switch ($_) {
1 { "one." }
2 { "two." }
3 { "three." }
}
}
1..3 | thing
使用expression):的
ScriptBlock.Create
method中的process
块)$com = '
process {
switch ($_) {
1 { "one." }
2 { "two." }
3 { "three." }
}
}
'
1..3 | & ([scriptblock]::Create($com))
ScriptBlock.InvokeWithContext
method和automatic variable $input
,这个技术不流,也需要一个外部scriptblock
才能工作,它只是为了展示,应该作为一个选项被丢弃:$com = '
switch ($_) {
1 { "one." }
2 { "two." }
3 { "three." }
}
'
1..3 | & { [scriptblock]::Create($com).InvokeWithContext($null, [psvariable]::new('_', $input)) }
Invoke-Expression
,还需要一个带有process
块的外部scriptblock
(应该放弃--从上面显示的所有技术来看-这是最糟糕的技术之一,字符串表达式是通过管道传递的每个项的计算值):$com = '
switch ($_) {
1 { "one." }
2 { "two." }
3 { "three." }
}
'
1..3 | & { process { Invoke-Expression $com } }
https://stackoverflow.com/questions/74636087
复制相似问题