I have the following code in PowerShell 5.1
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
...
try {
$scopes = Get-DhcpServerv4Scope -ComputerName $dhcphost -CimSession $dhcphostx
...
} catch {
Write-Warning "Failed to query local DHCP server! Server 2003 system?"
}
Some of the DHCP servers which the script will query are Server 2003 and on those servers, the code will fail. If the error is the following, the try...cath will get triggered and my warning will get displayed as expected
+ CategoryInfo : ResourceUnavailable: (PS_DhcpServerv4Scope:String) [Get-DhcpServerv4Scope], CimJobExcept ion
+ FullyQualifiedErrorId : CimJob_BrokenCimSession,Get-DhcpServerv4Scope
+ PSComputerName : S1773C01
But on the following error, the try...catch will not trigger
+ CategoryInfo : ObjectNotFound: (PS_DhcpServerv4Scope:root/Microsoft/...cpServerv4Scope) [Get-DhcpServerv4Scope], CimException
+ FullyQualifiedErrorId : HRESULT 0x80338000,Get-DhcpServerv4Scope
+ PSComputerName : S1761C01
The try...catch will ONLY trigger on both errors when setting the ErrorAction parameter
$scopes = Get-DhcpServerv4Scope -ComputerName $dhcphost -CimSession $dhcphostx -ErrorAction Stop
So ErrorActionPreference does not always throw and gets overridden by ErrorAction parameter in this case. Why is this happening and is there a way to have the global ErrorActionPreference ALWAYS throw an error?