简体   繁体   中英

Command works directly in Powershell but doesn't work when executed through a linux system using powershell

In a windows machine, if I open powershell and write this command, it works fine.

powershell -command "&{$p='It works'; echo $p}"

This outputs It works as intended.

But if I ssh into the same windows machine using a linux machine and try to execute this command, this gives me an error.

The command:

/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -command "&{$p='It works'; echo $p}"

When I execute this, the following error appears:

=It works : The term '=It works' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:3
+ &{='It works'; echo }
+   ~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (=It works:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


cmdlet Write-Output at command pipeline position 1
Supply values for the following parameters:
InputObject[0]:

I have searched a lot but couldn't find the reason behind it. I'd really appreciate it if someone could help me regarding this.

You need to escape the $ . Like this:

xxx@xxxxx:~$ pwsh -c "&{\$p='It works'; echo \$p}"
It works

Adding the example from @mklement0 , executing & a scriptblock { } (for this specific case) is not needed at all to which character escaping wouldn't be needed either:

xxx@xxxxx:~$ pwsh -c '$p="It works"; echo $p'
It works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM