Capture EXE output in PowerShell

前端 未结 5 2010
野趣味
野趣味 2020-12-09 02:40

A little background first.

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

相关标签:
5条回答
  • You need to use the --batch switch when automating GPG.EXE, as in:

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

    Without that switch, GPG may be waiting for user input.

    0 讨论(0)
  • 2020-12-09 02:45

    Stobor's answer is great. I am adding to his answer because I needed to perform additional actions if the exe had an error.

    You can also store the output of the exe into a variable like this. Then you can do error handling based on the result of the 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
    
    0 讨论(0)
  • 2020-12-09 02:52

    You also can use Out-Host as shown below.

    & $gpgLocation --import "key.txt" | Out-Host
    
    0 讨论(0)
  • 2020-12-09 02:53

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

    does this work?

    & $gpgLocation --import "key.txt" 2>&1 | out-file gpgout.txt
    
    0 讨论(0)
  • 2020-12-09 03:05

    Also, PowerShell simply can't capture the output of some programs because they don't write to stdout. You can verify this by running the program in PowerShell ISE (it's in the version 2.0 CTP 3)

    If PowerShell ISE can't show the output in the graphical console, then you can't capture it either and may need some other way of automating the program.

    0 讨论(0)
提交回复
热议问题