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

JBurace picture JBurace · Mar 15, 2013 · Viewed 55.1k times · Source

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?

Answer

aphoria picture aphoria · Mar 15, 2013

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