以下代码按预期工作:
'John' | % { "$_ $_" }
> John John
但是,我无法找到将字符串$_ $_
存储在变量中的方法,该变量稍后将在管道中使用:
$f = '$_ $_'
'John' | % { $f }
> $_ $_
我如何“插入”一个变量,而不是使用双引号字符串?
发布于 2014-04-08 16:43:05
您可以定义一个用大括号括起来的PowerShell ScriptBlock
,然后使用.
调用操作符执行它。
$f = { $_ $_ }
'John' | % { . $f }
输出如下所示:
John
John
或者,如果你想要一个字符串(就像你最初的问题一样),你可以这样做:
$f = { "$_ $_" }
'John' | % { . $f };
输出如下所示:
John John
发布于 2014-04-08 16:17:23
答案是
'John' | % { $ExecutionContext.InvokeCommand.ExpandString($f) }
> John John
这要归功于Bill_Stewart对PowerShell Double Interpolation的回答。
https://stackoverflow.com/questions/22942682
复制相似问题