How to pipe all output of .exe execution in Powershell?

纵然是瞬间 提交于 2019-11-29 07:09:27

问题


In Powershell I am running psftp.exe which is PuTTy's homepage. I am doing this:

$cmd = "psftp.exe"
$args = '"username@ssh"@ftp.domain.com -b psftp.txt';
$output = & $cmd $args

This works; and I am printing out $output. But it only catches some output in that variable (like "Remote working directory is [...]") and is throwing other output to an error type like this:

psftp.exe : Using username "username@ssh".
At C:\full_script.ps1:37 char:20
+         $output = & <<<<  $cmd $args
    + CategoryInfo          : NotSpecified: (Using username "username@ssh".:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

This "Using username ..." etc looks like a normal FTP message. How can I make sure all output gets put into $output?


回答1:


The problem is some output is being sent to STDERR and redirection works differently in PowerShell than in CMD.EXE.

How to redirect output of console program to a file in PowerShell has a good description of the problem and a clever workaround.

Basically, call CMD with your executable as a parameter. Like this:

UPDATE

I fixed my code so it would actually work. :)

$args = '"username@ssh"@ftp.domain.com -b psftp.txt';
$output = cmd /c psftp.exe $args 2`>`&1



回答2:


Give this a try

$output = [string] (& psftp.exe 'username@ssh@ftp.domain.com' -b psftp.txt 2>&1)

There is a PowerShell bug about 2>&1 making error records. The [string] cast works around it.



来源:https://stackoverflow.com/questions/15437244/how-to-pipe-all-output-of-exe-execution-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!