使用批处理文件 + powershell 脚本设置执行策略

使用批处理文件 + powershell 脚本设置执行策略

我正在处理我的点文件,我想创建一个批处理脚本,以便在切换到新计算机时为我进行一些初始设置,例如使用psget安装模块等...我还希望它继续将我的 ExecutionPolicy 更改为可用的内容。

我创建了一个批处理文件,它只是在 ExecutionPolicy 下触发一个 powershell 脚本Bypass

powershell -ExecutionPolicy ByPass 
           -NoLogo -NoProfile -NoExit 
           -File .\set-policy.ps1

set-policy.ps1尝试以管理员身份运行 powershell 来更改 ExecutionPolicy:

Start-Process powershell -verb runas 
  -ArgumentList "-No Exit -Command { Set-ExecutionPolicy Restricted }"

不幸的是,这个方法似乎不起作用(输出如下)。不知道问题出在哪里。

Set-ExecutionPolicy Restricted
PS C:\windows\system32> Get-ExecutionPolicy
RemoteSigned

关于如何使用批处理文件+ powershell 脚本来更改执行策略有什么提示吗?

答案1

问题在于您如何调用新的 PowerShell 进程;它似乎在 PowerShell 提示符准备好之前就执行了命令,因此这些命令只是被打印到控制台上;但我不确定为什么。无论如何,这是解决办法。

你的 set-policy.ps1 文件看起来应该是这样的:

Start-Process PowerShell -ArgumentList "Set-ExecutionPolicy Restricted -Force" -Verb RunAs

或者,您可以在批处理文件中用一行完成整个操作,如下所示:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList 'Set-ExecutionPolicy Restricted -Force' -Verb RunAs}"

我提供了有关从批处理文件调用 PowerShell 脚本的更多信息,以及为什么要这样做在我的博客文章中

答案2

对我来说,最简单的方法是编辑注册表。所以现在我的批处理文件只包含:

regedit.exe /S EnableScripts.reg

运行该程序将根据需要自动提示用户输入权限/凭据。我的EnableScripts.reg文件仅包含以下内容:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell]
"Path"="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
"ExecutionPolicy"="RemoteSigned"

上面的注册表设置已经足够了,除了运行 x86 PowerShell(在我的 64 位机器上)时。这需要另外设置以下注册表项:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell]
"Path"="C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe"
"ExecutionPolicy"="RemoteSigned"

相关内容