sourcecode

PowerShell에서 EXE 출력 캡처

codebag 2023. 10. 20. 13:38
반응형

PowerShell에서 EXE 출력 캡처

먼저 배경부터.

저는 GPG(gnupg.org )를 사용하여 파워셸 스크립트로 파일을 암호화하는 일을 수행했습니다.제가 부르는 특정한 전 부인은 그냥 gpg.exe입니다.명령을 실행할 때마다 출력을 캡처하고 싶습니다.

예를 들어 다음과 같이 파워셸의 공개 키를 가져옵니다.

& $gpgLocation --import "key.txt"

$gpgLocation은 단순히 gpg.exe의 파일 위치입니다(기본값은 "C:\프로그램 파일\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();

무슨 생각 있어요?절박해요!

기대하시는 출력이 표준 오류로 진행됩니까, 아니면 표준 출력으로 진행됩니까?

이게 먹히나요?

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

아래와 같이 Out-Host를 사용할 수도 있습니다.

& $gpgLocation --import "key.txt" | Out-Host

스토보르의 대답은 훌륭합니다.만약 전 부인에게 오류가 발생하면 추가 조치를 해야해서 그의 답변을 추가합니다.

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

또한 PowerShell은 stdout에 기록하지 않기 때문에 일부 프로그램의 출력을 캡처할 수 없습니다.PowerShell ISE(버전 2.0 CTP 3)에서 프로그램을 실행하여 이를 확인할 수 있습니다.

PowerShell ISE가 그래픽 콘솔에 출력을 표시할 수 없으면 출력도 캡처할 수 없으며 프로그램을 자동화하는 다른 방법이 필요할 수도 있습니다.

GPG를 자동화할 때 --batch 스위치를 사용해야 합니다.EXE, 다음과 같습니다.

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

해당 스위치가 없으면 GPG가 사용자 입력을 기다리고 있을 수 있습니다.

언급URL : https://stackoverflow.com/questions/919171/capture-exe-output-in-powershell

반응형