如何在Invoke-Expression -Command中转义“ @符号”(@)?

时间:2019-01-17 13:44:06

标签: powershell escaping powershell-v5.0

当我在命令行中运行此命令时,它会按预期工作:

C:\>p4 changes @2019/01/16,@now
...

但是当我在Powershell脚本中使用它时,我无法使其正常工作。

第一次尝试:

PS C:\> Invoke-Expression -Command "p4 changes @2018/01/16, @now"
Invoke-Expression : At line:1 char:25
+ p4 changes @2018/01/16, @now
+                         ~~~~
Splatted variables like '@now' cannot be part of a comma-separated list of arguments.
At line:1 char:1
+ Invoke-Expression -Command "p4 changes @2018/01/16, @now"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Invoke-Expression], ParseException
    + FullyQualifiedErrorId : SplattingNotPermittedInArgumentList,Microsoft.PowerShell.Commands.InvokeExpressionCommand

成功转义逗号:

PS C:\> Invoke-Expression -Command "p4 changes @2018/01/16',' @now"
p4 : Unintelligible revision specification '2018/01/16'.
At line:1 char:1
+ p4 changes @2018/01/16',' @now
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Unintelligible ...n '2018/01/16'.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

现在我认为问题出在某种程度上解释了“字符”(“ @”)。但是我未能使用多种方法对其进行转义。如何实现呢?

UPD 测试您的想法:

严重口音:

PS C:\> Invoke-Expression -Command "p4 changes `@2018/01/16',' `@now"
p4 : Unintelligible revision specification '2018/01/16'.
At line:1 char:1
+ p4 changes @2018/01/16',' @now
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Unintelligible ...n '2018/01/16'.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

单引号(逗号问题)

PS C:\> Invoke-Expression -Command 'p4 changes @2018/01/16, @now'
Invoke-Expression : At line:1 char:25
+ p4 changes @2018/01/16, @now
+                         ~~~~
Splatted variables like '@now' cannot be part of a comma-separated list of arguments.
At line:1 char:1
+ Invoke-Expression -Command 'p4 changes @2018/01/16, @now'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ParserError: (:) [Invoke-Expression], ParseException
    + FullyQualifiedErrorId : SplattingNotPermittedInArgumentList,Microsoft.PowerShell.Commands.InvokeExpressionCommand

2 个答案:

答案 0 :(得分:0)

停止使用双引号,如果您没有可扩展的内容,则使用单引号。请参阅about_quoting_rules

的文档

否则,就像其他人所说的那样,请使用反引号。

答案 1 :(得分:0)

工作解决方案:

        services.AddHealthChecks()
            .AddSqlServer("...")
            .AddApplicationInsightsPublisher();