danabb
danabb

Reputation: 65

Silence / Redirect PowerShell error stream: what am I missing?

I have a Powershell script to loosen the execution policy on a machine, essentially running:

Set-ExecutionPolicy Unrestricted -Force

Since ExecutionPolicy is restriced on the machine, I need to launch the .ps1 script using .bat file which bypasses the execution policy like this:

PowerShell.exe -ExecutionPolicy Bypass -File ./psscripts/myScript.ps1

By using this trick, I get the following error:

Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by
a policy defined at a more specific scope.  Due to the override, your shell will retain its current effective
execution policy of Bypass.

The error is trying to tell me that policy scope of the current process (launched with -Bypass) overrides the one I just set, but I don´t really care anyway, so I would like to simply hide this error.

I have tried using the -ErrorAction SilentlyContinue:

Set-ExecutionPolicy Unrestricted -Force -ErrorAction SilentlyContinue

But the error still displays. So I tried to redirect the error stream to &NULL like this:

Set-ExecutionPolicy Unrestricted -Force 2> $NULL

...but even like this, the error still pops up on the terminal.

I have successfully managed to silence the error using a try-catch like this:

try{Set-ExecutionPolicy Unrestricted -Force} catch {}

However, I would still like to understand why the two other approaches won´t work? Trying to redirect the error stream (or any stream) to a variable, the variable turns out empty, so I assume I am somehow trying to redirect the stream from the wrong process? Does this have something to do with launching Powershell from the .bat file?

Can anyone help me out here?

Upvotes: 3

Views: 509

Answers (1)

mklement0
mklement0

Reputation: 437408

Redirecting PowerShell's error output stream with 2> only works for non-terminating errors.

Note: The -ErrorAction common parameter operates exclusively on non-terminating errors as well - unlike the seemingly equivalent ErrorActionPreference preference variable, however, which - surprisingly - also applies to terminating errors - see the link to the GitHub docs issue below.

Set-ExecutionPolicy emits a terminating error, which only try / catch can handle (and the rarely used trap statement).

See also:

  • A description of PowerShell's fundamental error types in the context of guidance for command authors on when to emit a terminating vs. a non-terminating error: this answer.

  • A comprehensive overview of PowerShell's surprisingly complex error handling: this GitHub docs issue.

Upvotes: 3

Related Questions