【问题标题】:Command works directly in Powershell but doesn't work when executed through a linux system using powershell命令直接在 Powershell 中工作,但在使用 powershell 通过 linux 系统执行时不起作用
【发布时间】:2021-03-30 22:27:20
【问题描述】:

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

我搜索了很多,但找不到背后的原因。如果有人能帮助我解决这个问题,我将不胜感激。

【问题讨论】:

  • 去掉&符号&
  • 顺便说一句:请注意,没有理由使用 & { ... } 来调用通过 -command (-c) 参数传递给 PowerShell 的 CLI 的代码 - 只需直接使用 ...。旧版本的 CLI documentation 错误地建议 & { ... } 是必需的,但此后已更正。 /cc @AbrahamZinala
  • 在 Linux 主机上,可执行文件是 powershell 还是 pwsh

标签: powershell


【解决方案1】:

您需要转义$。像这样:

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

添加来自@mklement0 的示例,执行& 脚本块{ }(对于这种特定情况)根本不需要字符转义也不需要:

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

【讨论】:

    猜你喜欢
    • 2022-08-20
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2019-07-31
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多