Aug 05 2023 12:42 PM
My script logs into the CIMC of my Cisco servers to gather hardware information. There's one particular server which it seems the CIMC is not responding and instead of getting a "unable to connect" error from PowerShell, I'm getting
Write-Host "$StringLabel Error: $($PSItem.ToString())"
[MyServerName/172.2.12.167 Error: Object reference not set to an instance of an object.
I'm having difficulty capturing this exception. When I query the Exception type, I get:
$Error[0].Exception.GetType().FullName
System.NullReferenceException
However my Catch [System.NullReferenceException] statement is not picking it up. Instead my [System.Exception] Catch is picking it up?
Code is:
Try
{
# Let's connect to the CIMC.
$Connected = $True
Write-Host "$StringLabel Attempting a connection to server IMC." -ForegroundColor Yellow
$IMCHandle = Connect-IMC -Name $RackServerIMCIP -Credential $IMCServerCredential -NotDefault -ErrorAction Stop
}
Catch [System.NullReferenceException]
{
Write-Host "$StringLabel Error: $($PSItem.ToString())" -ForegroundColor Red
$Connected = $False
$ErrorPropertyValue = "Null Reference Error"
}
Catch [System.Exception]
{
# Did not connect due to connection issue.
Write-Host "$StringLabel Error: $($PSItem.ToString())" -ForegroundColor Red
If ($PSItem.Exception.ToString().Contains("Unable to connect"))
{
# Set connection flag false.
$Connected = $False
$ErrorPropertyValue = "Not Connected"
}
Else
{
$Connected = $False
$ErrorPropertyValue = "System Exception"
Write-Host "Not a connection issue." -ForegroundColor Red
}
}
Catch
{
Write-Host "$StringLabel Error: $($PSItem.ToString())" -ForegroundColor Red
$Connected = $False
$ErrorPropertyValue = "Unknown Error"
}
What am I doing wrong?
Aug 05 2023 06:11 PM
Solution
I can't see anything wrong with your code.
The only thing that makes sense to me is that the thrown exception is not actually of the type [System.NullReferenceException], but since I can't replicate your scenario, I'm simply making an educated guess.
From a diagnostic perspective, I'd verify the exception's type inheritance manually using:
try
{
Connect-IMC -Name $RackServerIMCIP -Credential $IMCServerCredential -NotDefault -ErrorAction:Stop
}
catch
{
$_.Exception.pstypenames;
}
Where the top-most type name is the most specific to the exception, becoming less so as you read downwards.
Here's a simple example to illustrate the output:
Cheers,
Lain
Aug 14 2023 05:46 PM