【问题标题】:Start-Job completes OK but output is reported as an errorStart-Job 完成正常但输出报错
【发布时间】:2013-09-25 22:30:46
【问题描述】:

我创建了一个 PowerShell 脚本,它将从 IIS 导出的 PFX 证书转换为更适合 Apache 的证书格式。该脚本使用一系列选项调用 openssl.exe 实例。它完美地工作。

我现在正在尝试处理用户友好的输出以及一些错误处理。我最初在 Invoke-Command 下运行该进程,正如我所说,它运行良好:

[string]$Command = " pkcs12 -in '$PFXFile' -nocerts -out '$key' -password pass:$importpw -passout pass:$pempw"
(Invoke-Command -ScriptBlock {param($arg)$arg|openssl.exe} -ArgumentList $Command)|Out-Null

这将从 OpenSSL 返回一条简单的成功消息(在本例中为“MAC 验证成功”)。我的目标是完全压制该信息,并用不那么简洁的东西代替它。我还没有找到一种方法来做到这一点,但我确实发现,当使用 Start-Job 运行相同的进程时:

[string]$Command = " pkcs12 -in '$PFXFile' -nocerts -out '$key' -password pass:$importpw -passout pass:$pempw"
Start-Job -ScriptBlock {param($arg)$arg|openssl.exe} -Name MakeCert -ArgumentList $Command
Get-Job|Wait-Job|Receive-Job

...同样的成功消息出现了,只是它现在似乎被标记为错误(红色文本):

    Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
    --     ----            -------------   -----         -----------     --------             -------
    1      MakeCert        BackgroundJob   Running       True            localhost            param($arg)$arg|openssl.exe
    MAC verified OK
    + CategoryInfo          : NotSpecified: (MAC verified OK:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : localhost

然后我尝试将 Start-Job 的 ErrorAction 定义为“停止”,然后他们将整个事情包装在 try/catch 中(使用 System.Exception 进行 catch)。但它给出了相同的输出。想法?

【问题讨论】:

    标签: powershell openssl pfx


    【解决方案1】:

    在这种情况下,在 Start-Job 上使用 -ErrorAction 将无济于事,因为 Start-Job 成功启动。执行 openssl.exe 后,立即输出 $LastExitCode 以查看 exe 是否返回非 0 退出代码。看起来 exe 正在写入 stderr,PowerShell 将其解释为错误。

    【讨论】:

    • 它似乎提供了一个 0 退出代码。刚刚运行$Command|openssl.exe;Write-Host $LastExitCode Returns: OpenSSL> MAC 验证正常;OpenSSL> 0
    • 那它一定是写到stderr了。我创建了一个简单的 C# 控制台应用程序,它写入 Console.Error 但返回 0。它在通过 Start-Job 运行时会产生相同的错误。
    【解决方案2】:

    我能够通过将 $error 对象转换为字符串,将其拆分为“+”,然后在包含任何 实际 错误消息时抛出不同的消息来获得所需的结果在字符串中。不是最优雅的解决方案,但可以让我到达我需要的地方。

    [string]$out = $Error[0]
    $message = $out.Split('+')[0]
    if($out -like '*invalid*' -or $out -like '*error*')
    {
        Write-Host 'ERROR:'
        Write-Host $command -Fore Yellow -Back Black
        Write-Host $message -Fore Red -Back Black
        throw('Process failed')
    }
    else
    {
        Write-Host $message -Fore White -Back DarkGreen
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 2021-08-22
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      相关资源
      最近更新 更多