Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 357
JBurace Avatar asked Mar 15 '13 16:03

JBurace


People also ask

How do you pipe the output of a command to a file in PowerShell?

There are two PowerShell operators you can use to redirect output: > and >> . The > operator is equivalent to Out-File while >> is equivalent to Out-File -Append . The redirection operators have other uses like redirecting error or verbose output streams.

Can you pipe in PowerShell?

Most PowerShell cmdlets are designed to support pipelines. In most cases, you can pipe the results of a Get cmdlet to another cmdlet of the same noun. For example, you can pipe the output of the Get-Service cmdlet to the Start-Service or Stop-Service cmdlets.


1 Answers

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 
like image 93
aphoria Avatar answered Sep 24 '22 19:09

aphoria