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

使用Powershell和Try Catch以及外部EXE解决重定向/捕获问题

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

    作为一名优秀的程序员,我在整个代码中使用try-catch块。当我调用GPG(gnupg.org)时,按如下方式传递几个命令:

    try `
    {
        & $gpgExeLocation --import $keyFileName 2>&1 | out-file "theOutput.txt";
    } `
    -Catch `
    {
        write-host "$_";
    }
    

    我得到一个空白文本文件(Output.txt)。

    但如果我打同样的电话 在try-catch块中,文本文件会按预期写入一些文本。

    这是我的try-catch实现

    function global:try
    {
        param
        (
            [ScriptBlock]$Command = $(Throw "The parameter -Command is required."),
            [ScriptBlock]$Catch   = { Throw $_ },
            [ScriptBlock]$Finally = {}
        )
    
        & {
            $local:ErrorActionPreference = "SilentlyContinue"
    
            trap
            {
                trap
                {
                    & {
                        trap { Throw $_ }
                        &$Finally
                    }
    
                    Throw $_
                }
    
                $_ | & { &$Catch }
            }
    
            &$Command
        }
    
        & {
            trap { Throw $_ }
            &$Finally
        }
    };
    
    1 回复  |  直到 12 年前
        1
  •  2
  •   Keith Hill    16 年前

    您似乎正在使用带有-Catch参数的自定义Try函数。介意分享一下你的实现,看看这是否会导致问题?

    function Get-CallStack {
        trap { continue }
        1..100 | foreach {
            $var = Get-Variable -scope $_ MyInvocation
            $var.Value.PositionMessage -replace "`n"
        }
    }
    
    #--------------------------------------------------------------------
    # Helper function to deal with legacy exe exit codes
    #--------------------------------------------------------------------
    function CheckLastExitCode {
        param ([int[]]$SuccessCodes = @(0), [scriptblock]$CleanupScript=$null)
    
        if ($SuccessCodes -notcontains $LastExitCode) {
            if ($CleanupScript) {
                "Executing cleanup script: $CleanupScript"
                &$CleanupScript
            }
            $OFS = $NL = [System.Environment]::NewLine
            throw "EXE RETURNED EXIT CODE ${LastExitCode}${NL}$(Get-CallStack)"
        }
    }
    

    & $gpgExeLocation --import $keyFileName 2>&1 | out-file "theOutput.txt"
    CheckLastExitCode
    
    推荐文章