简体   繁体   English

如何在 PowerShell 中无提示强制 session 级别执行策略?

[英]How to force session level execution policy without prompt in PowerShell?

I use the following code to rerun a script with admin privilege if necessary.如有必要,我使用以下代码重新运行具有管理员权限的脚本。

# 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
}

However, on some systems, when I right click the script and choose run with powershell , it will prompt me for something like yes, no, all, cancel... etc .但是,在某些系统上,当我右键单击脚本并选择使用 powershell 运行时,它会提示我输入yes、no、all、cancel... 等 I don't know exactly when this will happen.我不知道这会发生在什么时候。 How can I force the execution policy change without the prompt aforementioned?如果没有上述提示,如何强制执行策略更改? I checked the document and it seems there is no -force parameter for powershell .我检查了文档,似乎没有powershell-force参数。 There is a -force parameter for the cmdlet set-executionpolicy though.不过,cmdlet set-executionpolicy有一个-force参数。

The reason "why" sometimes get the prompt is because the account on some "systems" is already running it as Administrator(The elevation have already happened before at login or being disabled by GPO). “为什么”有时会收到提示的原因是因为某些“系统”上的帐户已经以管理员身份运行它(提升已经在登录之前发生或被 GPO 禁用)。 However, if you are running this on a remote machine, you will not need to elevate permissions if you already have admin rights to that machine, but running it from the current session would need the elevation unless the user is already signed as admin.但是,如果您在远程计算机上运行此程序,则如果您已经拥有该计算机的管理员权限,则无需提升权限,但从当前 session 运行它需要提升权限,除非用户已经以管理员身份签名。

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

On the other hand, I think there might be a better method for your usecase.另一方面,我认为您的用例可能有更好的方法。

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

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