I am utilising Azure Instance Metadata Service API. This will only work on an Azure VM, which is fine, but I want some error handling. The trouble is that when I run this on my development laptop (heavily locked down environment), I get our corporate proxy block page and nothing I try (no pun intended) will catch the block page and thus handle the error.
It is like the proxy intercepts the request before Invoke-RestMethod
can do anything.
Is there any way to catch the block message?
try
{
$oRequest = Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Uri "http://169.254.169.254/metadata/instance?api-version=2020-06-01"
}
catch [System.Net.WebException]
{
Throw "An error has occurred: $($_.exception.Message)"
}
$oRequest
is empty and even piping to Out-Null
doesn't stop the proxy block page message.
I appreciate this is really difficult to troubleshoot outside my corporate environment, but I am hoping someone may have experienced this behaviour and have a way of capturing the error.
The best I can come up with is a test to see if $oRequest
is empty and handle that, but this doesn't seem right and it still shows the block message in the PS console.
PowerShell version 7
T. I. A
Well, the reason you're getting the error is because you're catching the original error, then forcing another to occur by using
throw
. You already caught it, no need to throw another error. You can't pipe athrow
toout-null
because there is nothing to send to the pipeline.Also, though it may not be necessary at all times, it's good practice to
-ErrorAction Stop
on cmdlets that you wish to catch errors for.