In Ansible, how to set Execution-Policy to RemoteSigned? - powershell

I have an Ansible role that executes Powershell scripts. I do this
- name: Set the execution policy to Unrestricted first
win_shell: Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope LocalMachine -Force
tags: always
- name: Start the services
win_shell: C:\Users\Administrator\Desktop\Start_Services.ps1
args:
chdir: C:\Users\Administrator\Desktop\
when: exa_services_state == "started"
tags: always
- name: Stop the services
win_shell: C:\Users\Administrator\Desktop\Stop_Services.ps1
args:
chdir: C:\Users\Administrator\Desktop\
when: exa_services_state == "stopped"
tags: always
- name: Set the execution policy to RemoteSigned
win_shell: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine -Force
tags: always
However when the last task executes, I get the following
fatal: [10.227.26.97]: FAILED! => {"changed": true, "cmd": "Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine -Force", "delta": "0:00:00.640619", "end": "2022-03-04 05:33:29.496843", "msg": "non-zero return code", "rc": 1, "start": "2022-03-04 05:33:28.856224", "stderr": "Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by \r\na policy defined at a more specific scope. Due to the override, your shell will retain its current effective \r\nexecution policy of Unrestricted. Type \"Get-ExecutionPolicy -List\" to view your execution policy settings. For more \r\ninformation please see \"Get-Help Set-ExecutionPolicy\".\r\nAt line:1 char:65\r\n+ ... ing $false; Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope ...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n + CategoryInfo : PermissionDenied: (:) [Set-ExecutionPolicy], SecurityException\r\n + FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand", "stderr_lines": ["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 Unrestricted. Type \"Get-ExecutionPolicy -List\" to view your execution policy settings. For more ", "information please see \"Get-Help Set-ExecutionPolicy\".", "At line:1 char:65", "+ ... ing $false; Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope ...", "+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", " + CategoryInfo : PermissionDenied: (:) [Set-ExecutionPolicy], SecurityException", " + FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand"], "stdout": "", "stdout_lines": []}
If I go on the node and execute Get-ExecutionPolicy I see
PS: C:\Users\myuser>Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine RemoteSigned
How can I avoid the error? Thanks!

Your command actually succeeded(!) in principle, as evidenced by the wording of the error message.
If all you want to do is to set the local-machine policy for future sessions, you can simply ignore the error, by enclosing the statement in try / catch; also note the trailing ; exit 0 so as to ensure that exit code 0 is reported back to Ansible:
win_shell: try { Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine -Force } catch { }; exit 0
Note: If you're confident that you're running with elevation (which setting the machine policy requires), an empty catch block, as above, is probably sufficient.
A robust solution requires a bit more work:
win_shell: try { Set-ExecutionPolicy -Scope LocalMachine allSigned -force } catch { if ($_.FullyQualifiedErrorId -ne 'ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand') { throw } }; exit 0
This selectively ignores the anticipated error while re-throwing any others.
As an aside: It is unfortunate that the situation described by the error message, explained below, is surfaced as an error, let alone as a (statement)-terminating one. This is discussed in GitHub issue #12032, but a decision was made to retain this behavior for the sake of backward compatibility.
What the message is trying to tell you is that your execution policy will not take effect - in your case in the current session - because it is preempted by a less restrictive policy in a scope with higher precedence - see the conceptual about_Execution_Policies help topic.
Unfortunately, the error is also triggered for ad hoc, process-specific overrides (the Process scope), via the powershell.exe CLI's -ExecutionPolicy parameter, so that a command such as the following triggers it:
powershell -ExecutionPolicy Bypass -c Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
That is, the session in which the Set-ExecutionPolicy command executes has a process-specific execution policy of Bypass, and because the Process scope has higher precedence than the CurrentUser scope, and because the Bypass policy is less restrictive than RemoteSigned, the error occurs.
Technically, in that specific session itself the Set-ExecutionPolicy doesn't take effect (because the process-specific Bypass overrides it), but it will in future sessions (unless overridden again) - and if the sole intent of the CLI call was to set the persistent execution policy for future sessions, the error is nothing but a confusing annoyance.
I presume you're seeing this error because Ansible is using powershell -ExecutionPolicy Bypass (or Unrestricted) behind the scenes when it processes win_shell commands.

Related

PowerShell, cannot set execution policy to Unrestricted in Windows Sandbox

I have a startup script that runs during Window Sandbox startup that sets the execution policy while I am in that session.
$E = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
if ((Get-ExecutionPolicy -Scope LocalMachine) -ne "Unrestricted") {
Set-ExecutionPolicy Unrestricted -Scope LocalMachine -Force # Will always error if CurrentUser scope is set already
}
$ErrorActionPreference = $E
However, everytime tht script rung inside the Windows Sandbox, 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. Type "Get-ExecutionPolicy -List" to view
your execution policy settings. For more information please see "Get-Help
Set-ExecutionPolicy".
At C:\Users\WDAGUtilityAccount\Desktop\MySandbox\MySandbox.ps1:1198
char:3
+ Set-ExecutionPolicy Unrestricted -Scope LocalMachine -Force # W ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Set-ExecutionPolicy], Sec
urityException
+ FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Com
mands.SetExecutionPolicyCommand
When I list the policy inside the Sandbox session, I get:
PS C:\> Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine RemoteSigned
Why is the policy that I am trying to set, not being set (apparently)? Maybe the LocalMachine policy is being picked up from the Host system, but if so, how can I override that (this script the startup script that always runs with elevated privileges after all!)?

PowerShell, only run Set-Execution if it is not already set?

I have a script that tries to run these...
Set-ExecutionPolicy -scope CurrentUser RemoteSigned -Force -ea silent
Set-ExecutionPolicy RemoteSigned -Force -ea silent
But I get this 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. Type "Get-ExecutionPolicy
-List" to view your execution policy settings.
So I tried this:
if ($(Get-ExecutionPolicy) -ne "RemoteSigned") {
Set-ExecutionPolicy -scope CurrentUser RemoteSigned -Force -ea silent
Set-ExecutionPolicy RemoteSigned -Force -ea silent
}
But I get the same error (I thought this might skip the if body if I tried this.
I then tried
Set-ExecutionPolicy -Scope MachinePolicy Unrestricted
but I get this error:
Cannot set execution policy. Execution policies at the MachinePolicy or UserPolicy scopes must be set through Group
Policy.
But I don't use policies or anything AD related on my home system.
Get-ExecutionPolicy -list
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser RemoteSigned
LocalMachine RemoteSigned
How can I run the Set-Execution if the policy is not set, and skip that if it is not set?
The default scope is LocalMachine if you don't specify one. The message appears because CurrentUser takes priority over LocalMachine. One way to check is:
# [optional] temporarily suppress execution policy warnings
$E = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
if ((Get-ExecutionPolicy -Scope LocalMachine) -ne "RemoteSigned") {
# will always error if CurrentUser scope is set already
Set-ExecutionPolicy RemoteSigned -Scope LocalMachine -Force
}
if ((Get-ExecutionPolicy -Scope CurrentUser) -ne "RemoteSigned") {
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
}
$ErrorActionPreference = $E
The warning can't be suppressed normally since it's written directly to the console for some reason.
Alternatively, you can set only the CurrentUser scope. If you're not using group policy, then there are only three scopes to worry about. The highest one takes priority (setting lower ones will show the warning):
Process: Set for only the current process Set-ExecutionPolicy RemoteSigned -Scope Process
CurrentUser: Set for only the current user: Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
LocalMachine: Set for all users: Set-ExecutionPolicy RemoteSigned
For more information, check out about_Execution_Policies

Set-ExecutionPolicy unrestricted permission denied

I am trying to set the execution policy to Unrestricted, but I'm getting the following error:
PS> Set-ExecutionPolicy Unrestricted
Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic at
http://go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): Y
Set-ExecutionPolicy : Access to the registry key
'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. To change the execution
policy for the default (LocalMachine) scope, start Windows PowerShell with the "Run as administrator" option. To
change the execution policy for the current user, run "Set-ExecutionPolicy -Scope CurrentUser".
At line:1 char:1
+ Set-ExecutionPolicy unrestricted
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Set-ExecutionPolicy], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetExecutionPolicyComma
nd
Set-ExecutionPolicy defaults to setting the script execution policy for the whole system (implied -Scope LocalMachine).
-Scope LocalMachine can only be used from an elevated session (run as admin);[1] if your session isn't elevated, you'll get the error you saw - and the error text actually both explains the problem and provides instructions for how to resolve it.
To summarize:
Either: Re-run your command from an elevated session, assuming you have administrative credentials.
You can start one with Start-Process powershell -Verb RunAs (use pwsh in PowerShell (Core) 7+).
Or: Change the persistent execution policy only for the current user (-Scope CurrentUser)
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned -Force
Note:
I've chosen RemoteSigned as the policy in the sample call, as it provides a balance between security and convenience: it places no restriction on local scripts, but prevents execution of scripts downloaded from the web that aren't cryptographically signed.
-Force bypasses the interactive prompt.
While a current-user execution policy takes precedence over a local-machine one, both can be preempted by GPO-based policies - see this answer for more information.
There's also a way to set the execution policy for a single session only, via -Scope Process, though that is typically used via the PowerShell CLI (powershell.exe for Windows PowerShell, pwsh for PowerShell (Core) 7+), in the form of -ExecutionPolicy Bypass.
[1] While the same applies to PowerShell (Core) 7+ in principle, elevation is not required if you happen to have installed it in a current-user location. Also note that execution policies fundamentally do not apply when you use PowerShell (Core) 7+ on Unix-like platforms.

Cannot activate virtual environment in VSCode, despite updated ExecutionPolicy

I am trying to set up a virtual environment in VSCode.
For this I have created a folder 'newproject' using -m venv newproject in GitBash.
The problem is that I cannot activate the virtual environment because running scripts
is disabled on this system (below code is from the VSCode terminal):
./activate : File C:\Users\name\OneDrive\Dokumente\py_scripts\newproject\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For
more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ ./activate
./activate : File C:\Users\name\OneDrive\Dokumente\py_scripts\newproject\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For
more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ ./activate
+ ~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
I find this confusing, because I have tried setting the execution policies as admin via Powershell to both RemoteSigned and Unrestricted but I still get the error (below code is from PowerShell):
PS C:\windows\system32> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process
Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic at
https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): y
PS C:\windows\system32> Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process RemoteSigned
CurrentUser Undefined
LocalMachine Undefined
PS C:\windows\system32> Set-ExecutionPolicy Unrestricted -Scope Process
Execution Policy Change
The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose
you to the security risks described in the about_Execution_Policies help topic at
https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): y
PS C:\windows\system32> Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Unrestricted
CurrentUser Undefined
LocalMachine Undefined
Why do I still receive the error despite allowing locally written Scripts to be run?
Thank you!
I just figured it out.
One has to allow scripts within VSCode and not in a separate PowerShell window:
PS C:\Users\name\OneDrive\Dokumente\py_scripts\newproject\Scripts> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process
PS C:\Users\name\OneDrive\Dokumente\py_scripts\newproject\Scripts> ./activate
(newproject) PS C:\Users\mikes\OneDrive\Dokumente\py_scripts\newproject\Scripts>

Getting Set-ExecutionPolicy error while running any powershell script

I am getting below error while running any powershell script. It's happening on only one of the client's servers. I am not sure what is triggering this command.
If I change this registry key from RemoteSignedto to ByPass error goes away.
Set-ItemProperty -Path HKLM:\Software\Policies\Microsoft\Windows\PowerShell -Name ExecutionPolicy -Value ByPass
For example I have below simple script of one line.
Read-Host -Prompt "Hit Enter to exit"
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 RemoteSigned. Type "Get-ExecutionPolicy -List" to view your execution policy settings. For more
information please see "Get-Help Set-ExecutionPolicy".
At line:1 char:46
+ if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (:) [Set-ExecutionPolicy], SecurityException
+ FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand
Result from Get-ExecutionPolicy -List
Scope ExecutionPolicy
----- ---------------
MachinePolicy RemoteSigned
UserPolicy RemoteSigned
Process Undefined
CurrentUser Undefined
LocalMachine Unrestricted
You need to Run as Administrator and then try to Set-ExecutionPolicy..
or you can run powershell by this way also :
powershell.exe -ExecutionPolicy bypass
or
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope CurrentUser