try { # set the preference to STOP $old = $ErrorActionPreference $ErrorActionPreference = 'Stop' # RUN THE CONSOLE EXE THAT MIGHT EMIT AN ERROR, # and redirect the error channel #2 to the # output channel #1 net user doesnotexist 2>&1 }
catch [System.Management.Automation.RemoteException] { # catch the error emitted by the EXE, # and do what you want $errmsg = $_.Exception.Message Write-Warning$errmsg }
finally { # reset the erroractionpreference to what it was before $ErrorActionPreference = $old }
一个简单得多的办法是使用自定义作用域:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
& { try { # set the preference to STOP $ErrorActionPreference = 'Stop' # RUN THE CONSOLE EXE THAT MIGHT EMIT AN ERROR, # and redirect the error channel #2 to the # output channel #1 net user doesnotexist 2>&1 }
catch [System.Management.Automation.RemoteException] { # catch the error emitted by the EXE, # and do what you want: $errmsg = $_.Exception.Message Write-Warning$errmsg } }