首页 > 解决方案 > 如何在 PowerShell 中无提示强制会话级执行策略?

问题描述

如有必要,我使用以下代码重新运行具有管理员权限的脚本。

# Require admin
if(!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs
    exit
}

但是,在某些系统上,当我右键单击脚本并选择run with powershell时,它会提示我输入yes、no、all、cancel... 等内容。我不知道这会发生在什么时候。如果没有上述提示,如何强制执行策略更改?-force我检查了文档,似乎没有powershell. -force不过,cmdlet有一个参数set-executionpolicy

标签: powershellpromptexecutionpolicy

解决方案


“为什么”有时会得到提示的原因是因为某些“系统”上的帐户已经以管理员身份运行它(提升已经在登录之前发生或被 GPO 禁用)。但是,如果您在远程计算机上运行此程序,如果您已经拥有该计算机的管理员权限,则无需提升权限,但从当前会话运行它需要提升权限,除非用户已经以管理员身份签名。

在https://docs.microsoft.com/en-us/windows/security/identity-protection/user-account-control/how-user-account-control-works查看 Microsoft 的文档How User Account Control works

另一方面,我认为您的用例可能有更好的方法。


推荐阅读