SoFunction
Updated on 2025-03-10

Powershell implementation captures exceptions of system built-in EXE programs

All versions are supported.

When you run the console EXE command, such as, or similar commands. You can use Powershell to get the errors they cause:

Copy the codeThe code is as follows:

try
{
    $current = $ErrorActionPreference
    $ErrorActionPreference = 'Stop'
    # this will cause an EXE command to emit an error
    # (replace with any console-based EXE command)
    user nonexistentUser 2>&1
    $ErrorActionPreference = $current
}
catch
{
   Write-Host ('Error occured: ' + $_.)
}

To catch the error you need to set $ErrorActionPreference to $stop, at the same time, you need to change the output method of the error to add "2>&1"
After this setting, you can catch errors in .net through Powershell.