简体   繁体   中英

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 . 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 . There is a -force parameter for the cmdlet set-executionpolicy though.

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). 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.

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

On the other hand, I think there might be a better method for your usecase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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