如何在Powershell中管理.exe执行的所有输出?

时间:2013-03-15 16:16:31

标签: powershell output

在Powershell中,我正在运行psftp.exe这是PuTTy的主页。我这样做:

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

这有效;我正在打印$output。但它只捕获该变量中的一些输出(如“远程工作目录[...]”)并将其他输出抛出到这样的错误类型:

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

这个“使用用户名...”等看起来像普通的FTP消息。如何确保所有输出都放入$output

2 个答案:

答案 0 :(得分:15)

问题是某些输出正在发送到STDERR,并且重定向在PowerShell中的工作方式与CMD.EXE中的不同。

How to redirect output of console program to a file in PowerShell对问题有很好的描述,也有一个聪明的解决方法。

基本上,使用您的可执行文件作为参数调用CMD。像这样:

更新

我修复了我的代码,以便实际工作。 :)

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

答案 1 :(得分:6)

试一试

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

有一个PowerShell bug关于2>&1制作错误记录。 [string]演员围绕着它。

相关问题