通过SSH执行Powershell命令

1 投票
2 回答
11430 浏览
提问于 2025-04-16 19:59

我在Ubuntu主机上尝试了一个命令,想通过Cygwin/OpenSSH连接到Windows客户端。

ssh  USER@HOSTNAME  powershell -Command "& {Get-Host}"

输出结果是:

Cannot process the command because of a missing parameter. A command must follow -Command.

不过,当我在Windows客户端的Cygwin上执行同样的命令时,得到了正确的输出。

$ powershell -Command "& {Get-Host}"
Welcome to Powershell augmented with NaviNet tools.
Bootstrapped ScmToolsProjectConfiguration.


Name             : ConsoleHost
Version          : 2.0
InstanceId       : 0b2e578e-50b9-42ab-a07c-0c4ef762ba0c
UI               : System.Management.Automation.Internal.Host.InternalHostUser
CurrentCulture   : en-US
CurrentUICulture : en-US
PrivateData      : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace         : System.Management.Automation.Runspaces.LocalRunspace

2 个回答

0
ssh USER@HOSTNAME powershell -Command "& {Get-Host}"

当你运行这个命令时,本地系统上的ssh程序会接收到以下参数:

  • 用户@主机名
  • powershell
  • -Command
  • & {Get-Host}

最后一个参数的双引号在执行ssh之前会被你本地的命令行去掉。然后,ssh会把这三个参数合并成一个完整的字符串:

  • powershell -Command & {Get-Host}

这个字符串会被发送到远程系统去执行。但是,远程系统并没有按照你想要的方式来理解这个字符串。

你需要以一种方式来发出命令,确保引号包含在发送到远程系统的命令中。这样做应该可以解决问题:

ssh USER@HOSTNAME 'powershell -Command "& {Get-Host}"'
2

试着把 " 这个符号加上转义符,这样看起来像:

ssh USER@HOSTNAME powershell -Command \"& {Get-Host}\"

如果这样还不行,可以试着把 {、} 和 & 这些符号也加上转义符。我觉得这可能是转义的问题;)

编辑:

或者你可以试试用 \\\\" 来转义,这样会得到一个转义后的 " 和一个 \。我对 PowerShell 不太熟悉,不太清楚它需要什么样的命令。

撰写回答