2009-05-28 54 views
28

稍微背景優先。在PowerShell中捕獲EXE輸出

我的任務是使用GPG(gnupg.org)通過Powershell腳本加密文件。我打電話的具體exe只是gpg.exe。我想在執行命令時捕獲輸出。

舉例來說,我導入公鑰在PowerShell中,如下所示:

& $gpgLocation --import "key.txt" 

$ gpgLocation簡直是gpg.exe的文件位置(默認爲「C:\ Program Files文件\ GNU \ GnuPG的\ GPG .EXE」

我在這裏的整個問題是,如果我嘗試:

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

我得到的是一個1KB的文件,適當命名的,但它是完全空白的我試過幾個標誌對於出。文件只是爲了看如果我遇到了一個怪癖。

我也試着發送命令到該代碼(與通常的出文件等捕獲它的輸出):

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

任何想法?我很絕望!

+0

1的最後的代碼段,它覆蓋的缺省開始處理功能或者吃起來稱爲過程輸出,或將其寫入到文件中(但不向標準輸出) – 2011-07-18 12:57:37

回答

32

您期望的輸出是標準錯誤還是標準輸出?

能完成這項工作?

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

貌似2> $ 1作品!!!!我真誠地感謝所有你們花時間看這個!我是認真的! – CLR 2009-05-28 14:26:41

+2

另一個好的提示是,當使用這個時,stderr的任何輸出都將被包裝在ErrorRecord對象中。所以,如果你願意,你可以輕鬆處理錯誤輸出。 – JasonMArcher 2009-06-04 03:19:58

3

此外,PowerShell根本無法捕獲某些程序的輸出,因爲它們不寫入標準輸出。您可以通過在PowerShell ISE中運行程序來驗證此問題(版本爲2.0 CTP 3)

如果PowerShell ISE無法在圖形控制檯中顯示輸出,則無法捕獲它,並且可能需要一些其他自動化程序的方式。

+2

GPG當然不會直接操作控制檯屏幕緩衝區。或者,至少我會發現它很不可能只是需要某些輸出的UNIX程序會困擾詛咒。 – Joey 2009-05-28 06:49:50

3

您需要使用--batch開關時自動化GPG.EXE,如:沒有這個開關

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

,GPG可等待用戶輸入。

6

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

& $gpgLocation --import "key.txt" | Out-Host 
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 [email protected] -subject "Error in gpg " -body "Error:`n$out" -from [email protected] -smtpserver smtp.example.com 
} 
$out | out-file gpgout.txt