简体   繁体   English

更改PowerShell ExecutionPolicy的脚本

[英]Script to change PowerShell ExecutionPolicy

When I setup my system, I use a number of config scripts to have my cosy place to play. 设置系统时,我会使用许多配置脚本来放置自己喜欢的地方。

Based on this , I run by double-clicking the following enableps.js : 基于 ,我通过双击以下enableps.js

new ActiveXObject("Shell.Application").ShellExecute(
   "powershell", "-noexit -Command \"& Set-ExecutionPolicy RemoteSigned\"",  "", "runas");

Because of the -noexit I can issue in the displayed PowerShell window: 由于-noexit我可以在显示的PowerShell窗口中发出:

Get-ExecutionPolicy 

and get as expected: 并得到预期的结果:

RemoteSigned

Unfortunately, when opening a new instance of PowerShell, the policy keeps to be Restricted . 不幸的是,在打开PowerShell的新实例时,该策略始终处于Restricted

If I run in a standard cmd prompt: 如果我在标准cmd提示符下运行:

cscript  "path\to\enableps.js"

it works. 有用。 But if I embed the command in the enableps.cmd batch and again try to run it by double-clicking, it doesn't work. 但是,如果我将命令嵌入enableps.cmd批处理中,然后再次尝试通过双击运行它,它将无法正常工作。 If I right-click enableps.cmd and use the Runas-Administrator entry, it works again. 如果右键单击enableps.cmd并使用Runas-Administrator条目,它将再次起作用。

So how can I make things working with the standard double-click (plus the related Windows prompt)? 那么,如何通过标准双击(加上相关的Windows提示符)使事情正常进行?

You need to run the command and give it the -Scope argument so that it applies to more than the current session. 您需要运行命令并为其提供-Scope参数,以便它适用于当前会话以外的其他对象。 Add the argument: 添加参数:

-Scope CurrentUser

... and the solution is: ...,解决方案是:

Double click on the file: 双击文件:

// enableps.js
// -----------

new ActiveXObject("Shell.Application").ShellExecute(
   "powershell", "-Command \"Set-ExecutionPolicy RemoteSigned\" -Scope CurrentUser",  
   "", "runas");

Consider replacing RemoteSigned with Unrestricted to allow running downloaded scripts too. 考虑用Unrestricted替换RemoteSigned以也允许运行下载的脚本。

Credit goes to TheMadTechnician , who anyway did not write the full code. 归功于TheMadTechnician ,他始终没有编写完整的代码。

By default making system-wide changes will require you to elevate the process if it hasn't been elevated already. 默认情况下,如果尚未进行系统范围的更改,则需要提升该过程。 If you want your script to disable the execution policy at the machine level then you will either need to switch off UAC or else you will have to run your cscript using a shellExecute, which will present the user with the required UAC approval dialog. 如果希望脚本在计算机级别禁用执行策略,则需要关闭UAC,否则必须使用shellExecute运行cscript,这将向用户显示所需的UAC批准对话框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM