代码之家  ›  专栏  ›  技术社区  ›  CLR

在PowerShell中捕获EXE输出

  •  29
  • CLR  · 技术社区  · 16 年前

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

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

    & $gpgLocation --import "key.txt"
    

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

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

    我得到的只是一个1kb的文件,命名得当,但它完全是空的。我尝试了几个外文件的标志,只是想看看我是否遇到了怪癖。

    我还尝试向这段代码发送命令(并用通常的out文件等捕获输出):

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

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

    5 回复  |  直到 16 年前
        1
  •  33
  •   Stobor    16 年前

    这行得通吗?

    & $gpgLocation --import "key.txt" 2>&1 | out-file gpgout.txt
    
        2
  •  6
  •   Jon Chetan Kalore    14 年前

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

    & $gpgLocation --import "key.txt" | Out-Host
    
        3
  •  6
  •   jhamm    14 年前

    $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
    
        4
  •  3
  •   Josh    16 年前

    如果PowerShell ISE无法在图形控制台中显示输出,那么您也无法捕获它,可能需要其他方式来自动化程序。

        5
  •  3
  •   Ruben Bartelink    15 年前

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

    如果没有这个开关,GPG可能会等待用户输入。

    推荐文章