Powershell不会在脚本中捕获stderr变量

时间:2015-10-12 07:02:43

标签: powershell

我想通过Powershell脚本调用openssl,如果发生错误,请将stderr捕获到变量以记录错误。实际上,openssl错误是我想在这里看到的 - 这不是问题。我的问题是当openssl发生这样的问题时如何处理这种情况。

当我直接在Powershell中执行此操作时,它就像一个魅力:

PS > $bin = 'C:\OpenSSL-Win32\bin\openssl.exe'
PS > $parm =  'smime', '-encrypt', '-aes-256-gcm', '-outform', 'PEM', '-out', '<SomePathHere>\testd.xml.pem', '-in', '<SomePathHere>\testd.xml', '<SomePathHere>\Zert\part1.pem'
PS > & $bin $parm
Loading 'screen' into random state - done
Error opening recipient certificate file <SomePathHere>\part1.pem
2032:error:02001002:system library:fopen:No such file or directory:.\crypto\bio\bss_file.c:391:fopen('<SomePathHere>\part1.pem','rb')
2032:error:20074002:BIO routines:FILE_CTRL:system lib:.\crypto\bio\bss_file.c:393:
unable to load certificate
unable to write 'random state'

PS > $out = & $bin $parm 2>&1
PS > $out
openssl.exe : Loading 'screen' into random state - done
In Zeile:1 Zeichen:8
+ $out = & $bin $parm 2>&1
+        ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Loading 'screen...om state - done:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Error opening recipient certificate file <SomePathHere>\part1.pem
7228:error:02001002:system library:fopen:No such file or directory:.\crypto\bio\bss_file.c:391:fopen('<SomePathHere>\part1.pem','rb')
7228:error:20074002:BIO routines:FILE_CTRL:system lib:.\crypto\bio\bss_file.c:393:
unable to load certificate
unable to write 'random state'

当我将相同的代码放入脚本并将其作为脚本运行时,stderr不会将其放入变量中。有人知道我做错了吗?

以下是该脚本的相关代码:

        $OpenSSLParam = 'smime', '-encrypt', '-aes-256-gcm', '-outform', 'PEM', '-out', $OpenSSLAusgabeDatei, '-in', $OpenSSLEingabeDatei, $OpenSSLSchluessel
        $Old_ErrorActionPreference = $ErrorActionPreference
        $ErrorActionPreference = 'SilentlyContinue'
        $outssl = & $OpenSSLBinary $OpenSSLParam 2>&1
        if($LASTEXITCODE -ne 0)
        {
            $LogMsg = @"
OpenSSL-Fehler!
Exit Code: $LASTEXITCODE
Aufruf: $osslcmd
Error: $outssl
"@
            Write-EventLog -LogName Application -Source $EventlogSource -EventId 1002 -EntryType Error -Message $LogMsg
            exit $LASTEXITCODE
        }

如果我通过调试器运行它,我得到:

PS > <SomePathHere>\encrypt_xml.ps1
Treffer Zeilenhaltepunkt bei "<SomePathHere>\encrypt_xml.ps1:71"
[DBG]: PS >> $LASTEXITCODE
2

[DBG]: PS >> $outssl

[DBG]: PS >> 

我很想理解为什么Powershell不会填充$outssl变量。很感谢任何形式的帮助。作为一个礼物,我很想知道是否有一种方法可以在没有Powershell的stderr的情况下捕获openssl stderr。

1 个答案:

答案 0 :(得分:1)

好。我发现了这个问题。 Powershell表现得像所说的那样!

如果我更换

$ErrorActionPreference = 'SilentlyContinue'

$ErrorActionPreference = 'Continue'

我得到了理想的结果!