如何通过ssh从powershell脚本获取输出?

时间:2018-10-17 19:54:05

标签: windows powershell ssh

由于某种原因,我似乎无法获得输出和重定向来通过ssh从Linux移植到Windows。我有一个Powershell脚本,该脚本仅在每个流上输出一条消息。

在powershell终端中,它看起来像:

$ ssh me@windows.box.com
PS C:\Users\me> C:/"Program Files"/App3/bin/script.ps1 2> $null
This is output
This is to host
WARNING: This is a warning!
PS C:\Users\me> C:/"Program Files"/App3/bin/script.ps1 *>&1 2> $null
This is output
This is to host
WARNING: This is a warning!
C:\"Program Files"\App3\bin\script.ps1 : This is an error
At line:1 char:1
+ C:/"Program Files"/App3/bin/script.ps1 *>&1 2> $null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,script.ps1

但是由于某种原因,从ssh命令中,我无法将其他流重定向到stdout:

$ ssh me@windows.box.com "C:/\\\"Program Files\\\"/App3/bin/script.ps1" 2>/dev/null
This is output
This is to host
WARNING: This is a warning!
$ ssh me@windows.box.com "C:/\\\"Program Files\\\"/App3/bin/script.ps1 *>&1" 2>/dev/null
This is output
This is to host
WARNING: This is a warning!

并澄清这似乎是脚本特定的问题:

$ ssh me@windows.box.com "Write-Host \\\"This is to host\\\""
This is to host
$ ssh me@windows.box.com "Write-Output \\\"This is output\\\""
This is output
$ ssh me@windows.box.com "Write-Warning \\\"This is a warning\!\\\""
WARNING: This is a warning\!
$ ssh me@windows.box.com "Write-Error \\\"This is an error\\\""
Write-Error "This is an error" : This is an error
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException

关于如何重定向脚本输出的任何想法?

我确实遇到了另一个问题,那就是在脚本运行于不同目录时获取输出,但这是另一场战斗,另一篇Stack Overflow帖子。我正在运行RHEL,脚本内容为:

Write-Output "This is output"
Write-Host "This is to host"
Write-Verbose "This message is definitely more verbose"
Write-Debug "This is marked debug"
Write-Warning "This is a warning!"
Write-Error "This is an error"

1 个答案:

答案 0 :(得分:0)

我无法快速重新创建您的环境(Linux主机/ Windows远程)。我至少尝试模仿跨平台环境(Linux VM上的Powershell,Windows上的ssh客户端)。这里有一些说明可能会有所帮助,至少在您计划将这些流保存到文件中的情况下

与您不同,运行此命令时我在终端上得到了相同的输出

ssh mike@Ubuntu "/snap/bin/pwsh ./test.ps1 *>&1"  (on local)
pwsh ./test.ps1 *>&1  (on remote)

虽然在尝试通过ssh将输出重定向到文件时遇到了类似的问题(但如果从powershell会话中调用,则可以正常工作)

 ssh mike@Ubuntu "/snap/bin/pwsh ./test.ps1 *>&1 test.log" 
  #adds only original success to the file, and prints error on terminal

因此,如果通过ssh调用流到流的重定向似乎不起作用。尽管以某种方式流式归档似乎可行

 ssh mike@Ubuntu "/snap/bin/pwsh ./test.ps1 >test.log  2>>test.log" 
 ssh mike@Ubuntu "/snap/bin/pwsh ./test.ps1" &> test.log #redirection works again on local

所以可能是ssh / powershell交互的怪异错误。您可能会尝试使用标准的ps远程处理协议vs ssh(例如Invoke-Command {echo'hi'} -ComputerName YourMachine -Credentials $ creds)