Azure “抓不到”;“代理块页”;调用RestMethod/Try捕获被忽略时出错

Azure “抓不到”;“代理块页”;调用RestMethod/Try捕获被忽略时出错,azure,powershell,try-catch,invoke-restmethod,Azure,Powershell,Try Catch,Invoke Restmethod,我正在使用API。这只适用于Azure VM,这很好,但我需要一些错误处理。问题是,当我在我的开发笔记本电脑(高度锁定的环境)上运行这个时,我得到了我们的公司代理块页面,我尝试的任何东西(没有双关语)都不会捕捉块页面,从而处理错误 这就像代理在Invoke RestMethod可以做任何事情之前拦截请求一样 有没有办法捕捉到阻止消息 try { $oRequest = Invoke-RestMethod -Headers @{"Metadata"="true

我正在使用API。这只适用于Azure VM,这很好,但我需要一些错误处理。问题是,当我在我的开发笔记本电脑(高度锁定的环境)上运行这个时,我得到了我们的公司代理块页面,我尝试的任何东西(没有双关语)都不会捕捉块页面,从而处理错误

这就像代理在
Invoke RestMethod
可以做任何事情之前拦截请求一样

有没有办法捕捉到阻止消息

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
为空,即使管道传输到
输出Null
也不会停止代理阻止页面消息

我明白,在我的公司环境之外,这确实很难排除故障,但我希望有人可能经历过这种行为,并有一种捕获错误的方法

我能想到的最好办法是测试
$oRequest
是否为空并处理它,但这似乎不正确,它仍然在PS控制台中显示阻塞消息

PowerShell版本7


T.I.A

那么,您之所以会出现错误,是因为您捕获了原始错误,然后通过使用
throw
强制发生另一个错误。您已经捕获了它,无需再抛出一个错误。您不能通过管道将
抛出
发送到
输出null
,因为没有要发送到管道的内容

此外,尽管可能并非始终都有必要,但最好在希望捕获错误的cmdlet上执行
-ErrorAction Stop

try
{
    #This is where the exception will be thrown
    $oRequest = Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Uri "http://169.254.169.254/metadata/instance?api-version=2020-06-01" -ErrorAction Stop
}
catch [System.Net.WebException] #this catches the error that was thrown above and applies it to the built-in variable $_ for the catch's scope
{
    #if you uncomment the throw line, notice how you don't reach the next line,
    #this is because it creates a terminating error, and it's not handled with a try/catch
    #throw "bananas"
    $banana = "An error has occurred: $($_.exception.Message)"
}
Write-Host $banana

听起来这个错误是一个无终止错误。尝试在调用RestMethod命令时使用-ErrorAction停止脚本运行时是否可以运行Fiddler并捕获请求/响应对?这可能会对这个问题有所帮助。谢谢。我确实试过
-ErrorAction Stop
。从
捕获中删除
[System.Net.WebException]
修复了它。复制同事代码是我的错。