从批处理脚本中静默更改 Powershell 执行策略

Pap*_*oli 5 powershell command-line

我想要一些关于为 powershell 设置注册表值的帮助。路径是

[hkey_local_machine\system32\windows\microsoft\powershell\1\shellids\microsoft.powershell] "Path"="c:\windows\system32\windowspowershell\v1.0\powershell.exe" "ExecutionPolicy"="无限制"

因为我是从一台已知的好机器导入的,所以当我运行 .reg 文件时它工作正常。但我想在批处理文件中使用它。

当我手动调用命令提示符时,放入路径,例如c:\powershell.reg,这将导入值并根据需要覆盖注册表设置。
但是,如果我调用在批处理文件中执行相同的操作,则注册表中的值不会更改 在批处理文件中使用 reg add 命令,这些值不起作用。

meg*_*orf 11

为什么不简单地通过 CMD 运行以下命令

powershell -command "& {Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force}"
Run Code Online (Sandbox Code Playgroud)

或者直接在 Powershell 中(毕竟这就是命令的用途):

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force
Run Code Online (Sandbox Code Playgroud)


Dav*_*ill 1

如何通过批处理脚本静默更改 Powershell 执行策略?

警告:

以下说明包含告诉您如何修改注册表的步骤。但是,如果注册表修改不当,可能会出现严重问题。

因此,请确保您认真执行这些步骤。为了增强保护,请在修改注册表之前对其进行备份。然后,如果出现问题,您可以恢复注册表。

有关详细信息,请参阅如何在 Windows 中备份和还原注册表。


reg解决方案

@echo off
reg add HKLM\system32\windows\microsoft\powershell\1\shellids\microsoft.powershell /v "Path" /d "c:\windows\system32\windowspowershell\v1.0\powershell.exe"
reg add HKLM\system32\windows\microsoft\powershell\1\shellids\microsoft.powershell /v "ExecutionPolicy" /d "unrestricted"
Run Code Online (Sandbox Code Playgroud)

regedit解决方案

@echo off
regedit /s file.reg
Run Code Online (Sandbox Code Playgroud)

其中file.reg包含以下内容:

[hkey_local_machine\system32\windows\microsoft\powershell\1\shellids\microsoft.powershell] 
"Path"="c:\windows\system32\windowspowershell\v1.0\powershell.exe"
"ExecutionPolicy"="unrestricted"
Run Code Online (Sandbox Code Playgroud)

笔记:

  • [/s|-s]

    当在命令行上指定文件名时,此开关用于禁止通常显示的任何信息对话框。当应用程序的安装程序想要使用 .REG 文件执行 REGEDIT.EXE,但不希望用户被显示的任何对话框迷惑时,这非常有用。


进一步阅读

  • Windows CMD 命令行的 AZ 索引- 与 Windows cmd 行相关的所有内容的绝佳参考。
  • reg - 读取、设置或删除注册表项和值,从 .REG 文件保存和恢复。
  • regedit - 从文本 (.REG) 文件导入、导出或删除注册表设置。
  • regedit - 命令行开关。