为什么PowerShell中的变量扩展为`-encodedCommand`而不是其实际值?

时间:2018-10-09 13:03:18

标签: powershell

我希望$mydate变量或命令Get-Date -Format yyyy-MM-dd在以下命令行中展开(请注意curly braces required by the svn.exe client

$mydate = Get-Date -Format yyyy-MM-dd

svn log https://svn.apache.org/repos/asf/ -r {Get-Date -Format yyyy-MM-dd}

svn log https://svn.apache.org/repos/asf/ -r {$mydate}

在两种情况下,我都会遇到以下错误:

svn: E205000: Syntax error in revision argument '-encodedCommand'

为什么变量变成-encodedCommand?我应该摆脱大括号吗?怎么样?勾选“`”无效:

Error formatting a string: Input string was not in a correct format..
At line:1 char:1
+ svn log https://svn.apache.org/repos/asf/ -r `{$mydate`}

我在做什么错了?

2 个答案:

答案 0 :(得分:2)

我没有足够的意见要发表,但是请尝试:

svn log https://svn.apache.org/repos/asf/ -r "{$($mydate)}"

外部的引号将其全部转换为字符串,因此忽略花括号。$()允许正确解释变量(而不是字符串)。

答案 1 :(得分:2)

用背景信息补充yaquaholic's helpful answer

未用引号使用{...}在PowerShell中具有特殊含义:它创建了script block(脚本块),它是PowerShell的可重用部分可以作为参数传递或存储在变量中的代码,以便以后按需执行。

因此,传递带有嵌入式{}字符的参数,然后用 quote (带有'...'(文字字符串,例如'{foo}')或"..."(可根据需要扩展字符串,例如"{$foo}")。


PowerShell自Windows PowerShell v5.1 / PowerShell Core 6.1.0起带有未加引号 {...}的行为是known problem

脚本块在PowerShell的外部中没有任何意义,例如在将参数传递给svn之类的外部程序时。

相比之下,使用脚本块 is 调用 PowerShell自己的CLI -powershell.exe(Windows PowerShell),pwsh(PowerShell Core)-通过脚本块内容的幕后Base64编码支持,并通过-encodedCommand传递编码后的字符串,并将CLIXML序列化应用于参数和管道输入-请参见this comment on GitHub

该机制目前(也毫无意义)也应用于其他外部程序,这就是为什么看到-encodedCommand参数的原因。