All Versions
When you run native console EXE commands such as robocopy.exe, ipconfig.exe, or similar commands, you can handle errors raised by these commands:
try { $current = $ErrorActionPreference $ErrorActionPreference = 'Stop' # this will cause an EXE command to emit an error # (replace with any console-based EXE command) net.exe user nonexistentUser 2>&1 $ErrorActionPreference = $current } catch { Write-Host ('Error occured: ' + $_.Exception.Message) }
To catch an error, you need to temporarily set $ErrorActionPreference to “Stop”. In addition, you need to redirect the error channel to the output channel by adding “2>&1”.
If you do this, the error can be handled by PowerShell like any .NET error.