好吧,你得到错误的原因是因为你捕捉到了原来的错误,然后用
throw
. 你已经捕捉到了,不需要再抛出一个错误。你不能用管道
out-null
因为没有东西要送到管道里。
-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