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?