簡體   English   中英

命令直接在 Powershell 中工作,但在使用 powershell 通過 linux 系統執行時不起作用

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

在 windows 機器中,如果我打開powershell並編寫此命令,它工作正常。

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

這輸出It works

但是,如果我使用 linux 機器將ssh放入同一台 windows 機器並嘗試執行此命令,這會給我一個錯誤。

命令:

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

當我執行此操作時,會出現以下錯誤:

=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]:

我搜索了很多,但找不到背后的原因。 如果有人可以幫助我解決這個問題,我將不勝感激。

您需要轉義$ 像這樣:

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

添加來自@mklement0的示例,根本不需要執行&一個 scriptblock { } (對於這種特定情況),也不需要字符 escaping :

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM