Set-ExecutionPolicy unrestricted permission denied - powershell

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.

Related

Why is the PyCharm Terminal showing "activate.ps1 cannot be loaded because running scripts is disabled on this system"? [duplicate]

This question already has answers here:
PowerShell says "execution of scripts is disabled on this system."
(48 answers)
Closed 8 months ago.
When I try to run ionic commands like ionic serve on the VS Code terminal, it gives the following error.
How can I fix this?
ionic : File C:\Users\Lakshan\AppData\Roaming\npm\ionic.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
+ ~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
I found a way to fix this error.
It is as follows:
First, Open PowerShell with Run as Administrator.
Then, run this command in PowerShell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
After that type Y and press Enter.
This is because of Execution Policy. This defines how powershell scripts will run.
In Default windows desktops, it is Restricted, not allowing any scripts (signed or unsigned) only interactive sessions.
So best is you set using RemoteSigned (Default on Windows Server) letting only signed scripts from remote and unsigned in local to run, but Unrestriced is insecure lettting all scripts to run.
To set run Set-ExecutionPolicy -ExecutionPolicy RemoteSigned as administrator.
This code will fix it:
Set-ExecutionPolicy RemoteSigned –Scope Process
To Bypass this you need to change the Execution policy.
Type this into your terminal.
Set-ExecutionPolicy -Scope CurrentUser
then it will prompt you to supply a value at which point you can set Bypass / RemoteSigned or Restricted.
cmdlet Set-ExecutionPolicy at command pipeline position 1
Supply values for the following parameters:
ExecutionPolicy: "RemoteSigned" or "Bypass" or "Restricted".

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

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.

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>

How to fix "running scripts is disabled on this system"? [duplicate]

This question already has answers here:
PowerShell says "execution of scripts is disabled on this system."
(48 answers)
Closed 8 months ago.
When I try to run ionic commands like ionic serve on the VS Code terminal, it gives the following error.
How can I fix this?
ionic : File C:\Users\Lakshan\AppData\Roaming\npm\ionic.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
+ ~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
I found a way to fix this error.
It is as follows:
First, Open PowerShell with Run as Administrator.
Then, run this command in PowerShell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
After that type Y and press Enter.
This is because of Execution Policy. This defines how powershell scripts will run.
In Default windows desktops, it is Restricted, not allowing any scripts (signed or unsigned) only interactive sessions.
So best is you set using RemoteSigned (Default on Windows Server) letting only signed scripts from remote and unsigned in local to run, but Unrestriced is insecure lettting all scripts to run.
To set run Set-ExecutionPolicy -ExecutionPolicy RemoteSigned as administrator.
This code will fix it:
Set-ExecutionPolicy RemoteSigned –Scope Process
To Bypass this you need to change the Execution policy.
Type this into your terminal.
Set-ExecutionPolicy -Scope CurrentUser
then it will prompt you to supply a value at which point you can set Bypass / RemoteSigned or Restricted.
cmdlet Set-ExecutionPolicy at command pipeline position 1
Supply values for the following parameters:
ExecutionPolicy: "RemoteSigned" or "Bypass" or "Restricted".

Why can't I get the Jenkins Powershell plugin to work?

Why can't I get the Jenkins "Powershell plugin" to work?
I can run a powershell script on Jenkins using a "Execute windows batch command" build step with the following command:
powershell -ExecutionPolicy ByPass -File script.ps1
But I am unable to run a powershell script with the Jenkins "Powershell plugin" using the "Windows Powershell" build step and this command, because of a Windows Execution policy not set error disallowing it to run:
script.ps1
Does anyone know the proper arg to give the Jenkins "Powershell Plugin" for it to succesfully run a script? Otherwise, I will just use the batch script work-around.
The correct thing to do is to set an execution policy on your machine (a one-time action), at which point you won't need to bypass it every time, and the Jenkins plugin should "just work". Are you unable to?
A reasonable starting setting would be RemoteSigned, which will allow you to execute local scripts fine but would still disallow scripts downloaded from the internet.
From an elevated PowerShell prompt, you would run:
Set-ExecutionPolicy RemoteSigned
See also: http://technet.microsoft.com/library/hh849812.aspx
UPDATE: excerpt from Help on applying policy and how it's supposed to behave:
If you set the execution policy for the local computer (the default)
or the current user, the change is saved in the registry and remains
effective until you change it again.
Of course, if your machine is on a Domain, then Group Policy could revert this.
For a reboot-proof solution, put this single line
powershell Set-ExecutionPolicy -Scope CurrentUser RemoteSigned -Force
in a batch file in the All Users Startup folder, which on Windows 7 is C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
(or you can get there by clicking Start -> All Programs, right-click Startup and click Open All Users)
This is how I got Jenkins executing PS scripts on a domain machine subject to Group Policy, without having to involve the sys admin guys ;-)
After experimentation, I realized that since Jenkins is running as a service as the System user, then the powershell scope is different than the scope used by my terminal services login session.
This script works for me and seems to properly set the registry keys so that the setting is persistent across reboots and new logins.
# SetExecutionPolicyToRemoteSigned.ps1
# Need to run this after every server reboot.
Write-Output "Setting local Powershell policy to RemoteSigned"
Write-Output ""
Set-ExecutionPolicy -scope CurrentUser Undefined -Force
#Set-ExecutionPolicy -scope Process Undefined -Force
Set-ExecutionPolicy -scope LocalMachine Undefined -Force
Set-ExecutionPolicy -scope CurrentUser RemoteSigned -Force
#Set-ExecutionPolicy -scope Process RemoteSigned -Force
Set-ExecutionPolicy -scope LocalMachine RemoteSigned -Force
Write-Output "Finished."
Get-ExecutionPolicy -list
Start-Sleep -s 10