Search code examples
powershellescapingpowershell-5.0

How to escape "at sign" (@) in Invoke-Expression -Command?


When I run this command in command-line, it works as expected:

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

But when I use it in powershell script, I can't get it working.

First attempt:

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

Escaping comma (successfully):

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

Now I think the problem is in "at character" ("@") being interpreted on some level. But I've failed to escape it using multiple methods. How to achieve this?

UPD Testing your ideas:

Grave Accent:

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

Single quote (problem with comma):

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

Solution

  • Working solution:

    $cmd = @'
    p4 changes @2018/01/16','@now
    '@;    
    Invoke-Expression $cmd