在 PowerShell 中捕获 EXE 输出 [英] Capture EXE output in PowerShell

查看:63
本文介绍了在 PowerShell 中捕获 EXE 输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

先介绍一下背景.

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

I've been tasked with encrypting files with a Powershell script using GPG (gnupg.org). The specific exe I'm calling is simply gpg.exe. I'd like to capture the output whenever I execute a command.

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

For instance, I import a public key in powershell as follows:

& $gpgLocation --import "key.txt"

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

$gpgLocation is simply the file location of gpg.exe (default being "C:\Program Files\GNU\GnuPG\gpg.exe"

我的整个问题是,如果我尝试:

My entire issue here is that if I try:

& $gpgLocation --import "key.txt" | out-file gpgout.txt

我得到的只是一个 1kb 的文件,命名适当,但它完全是空白的.我已经为输出文件尝试了几个标志,只是为了看看我是否遇到了怪癖.

All I get is a 1kb file, named appropriately, but it is COMPLETELY blank. I've tried several flags for out-file just to see if I was running into a quirk.

我还尝试将命令发送到此代码(并使用通常的输出文件等捕获输出):

I've also tried sending the command to this code (and capturing the output with the usual out-file etc):

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();

有什么想法吗?我很绝望!

Any ideas? I'm desperate!

推荐答案

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

Does the output you're expecting go to standard-error or standard-out?

这行得通吗?

& $gpgLocation --import "key.txt" 2>&1 | out-file gpgout.txt

这篇关于在 PowerShell 中捕获 EXE 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆