Domanda

I have created a PowerShell script that converts PFX certificates exported from IIS to a certificate format that works better with Apache. The script invokes an instance of openssl.exe with a series of option. It work perfectly.

I am now trying to work in user-friendly output as well as some error handling. I was running the process under Invoke-Command initially and, as I said, that was working well:

[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

That would return a simple success message from OpenSSL (in this case, "MAC verified OK"). My goal is to suppress that message entirely and replace it with something less terse. I have yet to find a way to do that but I did find that, when running the same process using Start-Job thusly:

[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

...the same success message appeared, except it seemed to now be flagged as an error (red text):

    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

I then tried defining the ErrorAction of Start-Job to 'stop' and them wrapping the whole thing in a try/catch (using System.Exception for the catch). But it gave the same output. Thoughts?

È stato utile?

Soluzione 2

I was able to get the results I needed by converting the $error object to a string, splitting it on the '+', and then throwing a different message if any actual error messages are contained in the string. Not the most elegant solution but gets me where I need to be.

[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
}

Altri suggerimenti

Using -ErrorAction on Start-Job won't help in this case because Start-Job starts successfully. Right after you execute openssl.exe, output $LastExitCode to see if the exe is returning a non-0 exit code. It looks like the exe is writing to stderr which PowerShell interprets as, well, an error.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top