如何在没有提示的情况下在 PowerShell 中强制执行会话级执行策略?

How to force session level execution policy without prompt in 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
}

但是,在某些系统上,当我右键单击脚本并选择 运行 with powershell 时,它会提示我输入 yes 、不、全部、取消……等等。我不知道这会在什么时候发生。如何在没有上述提示的情况下强制执行策略更改?我查看了文档,似乎 powershell 没有 -force 参数。不过,cmdlet set-executionpolicy 有一个 -force 参数。

"why" 有时得到提示的原因是因为某些 "systems" 上的帐户已经 运行 作为管理员(提升已经在登录时发生或被禁用GPO)。 但是,如果您 运行 在远程机器上使用此机器,并且您已经拥有该机器的管理员权限,则无需提升权限,但 运行 当前会话中的它需要提升权限,除非用户已经以管理员身份登录。

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

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