0

I am invoking a lot of REST calls in a function. I know that some of them will fail, but that is expected.

My question is:

How do I prevent powershell from adding entries to the global $error variable?

foreach:

$oldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "Ignore"
try {
    $response = Invoke-RestMethod -Uri $Uri -ea Ignore
} catch {
    Write-Verbose "$_"
} finally {
    $ErrorActionPreference = $oldErrorActionPreference
}

$error variable after invoking:

enter image description here

4
  • 1
    Doesn't $Error store all the errors that have occurred in a Powershell session? It would be much safer to user $error[0] to look at the latest error, then slowly move up the array if required. Commented Aug 9, 2019 at 7:48
  • 3
    Why would you even want to? What is the problem you're trying to solve? Commented Aug 9, 2019 at 8:34
  • @AnsgarWiechers I am creating a set of core modules, that in themselves must be non-leaking to $global:error. Commented Aug 10, 2019 at 14:01
  • The exception is "expected" - and is therefore not an error. I do not like that an exceptional state that my code have "accepted", still leaks to global:error. This creates an overloaded $error, that again then cannot be used for tracking and finding real "errors" Commented Aug 10, 2019 at 14:02

1 Answer 1

2

Invoke-RestMethod cmdlet always fails with terminating error, which can't be Ignored — it will always end up inside $Error list.

You can clear it: $Error.Clear()

Sign up to request clarification or add additional context in comments.

3 Comments

Source for this?
@CasperLeonNielsen about Invoke-RestMethod always throwing terminating errors can be deduced from here: github.com/PowerShell/PowerShell/blob/master/src/…
@CasperLeonNielsen PowerShell error handling and what and when goes into $Error variable explained (in length) here: github.com/MicrosoftDocs/PowerShell-Docs/issues/1583

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.