Reputation: 3490
I'm running an app in PowerShell like so:
$exe = "C:\blah\build\blah\Release\blahblah.exe"
&$exe scheduledRun sliceBicUp useEditionId
blahblah.exe
is a C# .NET 4.5 Console App. Now I know this executable can throw errors etc. Can I catch these errors/exceptions within the PowerShell script itself?
Basically i want the PowerShell script to detect an error/exception has occurred and action something, like email our Helpdesk for example.
Upvotes: 0
Views: 898
Reputation: 17462
you can use this code. When .Net program exit then error is passed to ps script
$exe = "C:\Users\johnn\OneDrive\Documents\visual studio 2015\Projects\test\test\bin\Release\test.exe"
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $exe
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "localhost"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$stdout = $p.StandardOutput.ReadToEnd()
$stderr = $p.StandardError.ReadToEnd()
Write-Host "stdout: $stdout"
Write-Host "stderr: $stderr"
Write-Host "exit code: " + $p.ExitCode
Upvotes: 1
Reputation: 200233
As @Liam mentioned, errors from external programs are not exceptions. If the executable terminates with a proper exit code you could check the automatic variable $LastExitCode
and react to its value:
& $exe scheduledRun sliceBicUp useEditionId
switch ($LastExitCode) {
0 { 'success' }
1 { 'error A' }
2 { 'error B' }
default { 'catchall' }
}
The only other thing you could do is parse the output for error messages:
$output = &$exe scheduledRun sliceBicUp useEditionId *>&1
if ($output -like '*some error message*') {
'error XY occurred'
}
Upvotes: 2