Showing the UAC prompt in PowerShell if the action requires elevation

笑着哭i 提交于 2019-11-28 06:30:31

AFAIK, there is no way to do it in the sense that you seem to want. That is running a specified .exe and expecting a prompt to appear immediately.

What I do is for commands that I know have to be run with administrative privs, I run them with a functions I have laying around called Invoke-Admin. It ensures that I'm running as admin and will prompt the user with the UAC dialog if i'm not before running the command.

Here it is

function Invoke-Admin() {
    param ( [string]$program = $(throw "Please specify a program" ),
            [string]$argumentString = "",
            [switch]$waitForExit )

    $psi = new-object "Diagnostics.ProcessStartInfo"
    $psi.FileName = $program 
    $psi.Arguments = $argumentString
    $psi.Verb = "runas"
    $proc = [Diagnostics.Process]::Start($psi)
    if ( $waitForExit ) {
        $proc.WaitForExit();
    }
}

First install PowerShell Community Extensions choco install pscx via Chocolatey (you may have to restart your shell environment)

then enable pscx

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser #allows scripts to run from the interwebs, such as pcsx

Then use Invoke-Elevated, for example

Invoke-Elevated {Add-PathVariable $args[0] -Target Machine} -ArgumentList $MY_NEW_DIR

This script sectio check for the Medium Mandatory level token (non elevated admin) and restarts the script elevated.

if ($Mygroups -match ".*Mandatory Label\\Medium Mandatory Level") {
  #non elevated admin: elevating
  write-host "Elevate"
  start-process powershell -Argumentlist "$PSCommandPath  -Yourargument $Youragumentvalue" -verb runas -Wait 
  exit
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!