在PowerShell中捕获EXE输出

CLR*_*CLR 28 powershell

先是一点背景.

我的任务是使用GPG(gnupg.org)使用Powershell脚本加密文件.我正在调用的特定exe只是gpg.exe.我想在执行命令时捕获输出.

例如,我在powershell中导入一个公钥,如下所示:

& $gpgLocation --import "key.txt"
Run Code Online (Sandbox Code Playgroud)

$ gpgLocation只是gpg.exe的文件位置(默认为"C:\ Program Files\GNU\GnuPG\gpg.exe"

我的全部问题是,如果我尝试:

& $gpgLocation --import "key.txt" | out-file gpgout.txt
Run Code Online (Sandbox Code Playgroud)

我得到的只是一个1kb文件,名称相应,但它完全是空白的.我已经为out-file尝试了几个标志,看看我是否遇到了怪癖.

我也尝试将命令发送到此代码(并使用通常的out-file等捕获输出):

param
(
    [string] $processname, 
    [string] $arguments
)

$processStartInfo = New-Object System.Diagnostics.ProcessStartInfo;
$processStartInfo.FileName = $processname;
$processStartInfo.WorkingDirectory = (Get-Location).Path;
if($arguments) { $processStartInfo.Arguments = $arguments }
$processStartInfo.UseShellExecute = $false;
$processStartInfo.RedirectStandardOutput = $true;

$process = [System.Diagnostics.Process]::Start($processStartInfo);
$process.WaitForExit();
$process.StandardOutput.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?我很绝望!

Sto*_*bor 35

您期望的输出是标准错误还是标准输出?

这有用吗?

& $gpgLocation --import "key.txt" 2>&1 | out-file gpgout.txt
Run Code Online (Sandbox Code Playgroud)

  • 另一个好的提示是,当使用它时,stderr的任何输出都将包装在ErrorRecord对象中.因此,如果需要,您可以轻松处理错误输出. (2认同)

小智 7

您也可以使用Out-Host,如下所示.

& $gpgLocation --import "key.txt" | Out-Host
Run Code Online (Sandbox Code Playgroud)


jha*_*amm 6

Stobor的答案很棒.我正在添加他的答案,因为如果exe有错误我需要执行其他操作.

您还可以将exe的输出存储到这样的变量中.然后你可以根据exe的结果进行错误处理.

$out = $gpgLocation --import "key.txt" 2>&1
if($out -is [System.Management.Automation.ErrorRecord]) {
    # email or some other action here
    Send-MailMessage -to me@example.com -subject "Error in gpg " -body "Error:`n$out" -from error@example.com -smtpserver smtp.example.com
}
$out | out-file gpgout.txt
Run Code Online (Sandbox Code Playgroud)