As stated in above comment you've to define the ErrorPreference
of the Invoke-RestMethod
cmdlet. This can be either done by the -ErrorAction
parameter (and setting its value to Stop
), or via the $ErrorPreference
"global" variable.
From devblog:
In reality, this means that if an error occurs and Windows PowerShell can recover from it, it will attempt to execute the next command. But it will let you know the error occurred by displaying the error to the console.
So for non-terminating
errors you've to define if PowerShell shall stop execution or simply continue the execution.
Below code sets the ErrorAction
to Stop
so a non-terminating error will be caught. When will PowerShell detect a terminating error, or what is a terminating error? For example, if you run out of memory, or if PowerShell detects a syntax error.
Since the Invoke-RestMethod docu states:
Windows PowerShell formats the response based to the data type. For an RSS or ATOM feed, Windows PowerShell returns the Item or Entry XML nodes. For JavaScript Object Notation (JSON) or XML, Windows PowerShell converts (or deserializes) the content into objects.
$response
may either contain XML or JSON (or something else specific) that PowerShell tries to parse.
Update1: Based on below comment stating an error message, $response
contains XML, that PowerShell converts. At the end $response
should have a Error status
property in case of an error. With the help of Get-Member
we can check if $response
contains an error property and perform additional error handling.
try
{
$uri = "https://my url"
$response = Invoke-RestMethod -Uri $uri -ErrorAction Stop
# Was a valid response object returned?
if ($null -ne $response) {
# Has the object an REST-API specific Error status property?
if(Get-Member -inputobject $response-name "UnknownResult" -Membertype Properties){
Write-Error "response contains error $response"
Write-Error "$($response.UnknownResult.Error.Message)"
}
else {
# No error detected, save the response
$response.Save("C:\Users\rtf\Desktop\Details\samplet.xml")
Write-Host "done" -ForegroundColor Magenta
}
}
}
catch
{
$_.Exception
}
You can play around with the xml code under this link.