如果操作需要提升,则在 PowerShell 中显示 UAC 提示 [英] Showing the UAC prompt in PowerShell if the action requires elevation

查看:27
本文介绍了如果操作需要提升,则在 PowerShell 中显示 UAC 提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 PowerShell 脚本来停止进程:

I have a simple PowerShell script to stop a process:

$p = get-process $args
if ( $p -ne $null )
{
$p | stop-process
$p | select ProcessName, ID, HasExited, CPU, Handles
}
else { "No such process" }

如果我尝试停止当前用户未启动的进程;它适用于 Windows Server 2003.但是,在 Windows Server 2008(以及具有用户帐户控制的其他 Windows 版本)上,我收到以下错误:

If I try to stop a process not started by the current user; it works on Windows Server 2003. However, on Windows Server 2008 (and other Windows flavours with User Account Control), I get the following error:

Stop-Process : Cannot stop process "w3wp (5312)" because of the following error: Access is denied

有没有办法在不以提升的权限运行 PowerShell 的情况下解决这个问题?如果用户每次尝试执行需要提升的操作时,只要看到 UAC 提示就可以了.

Is there any way to get around this without running PowerShell with elevated privileges ? It would be OK if the user was just presented with the UAC prompt, whenever he tries to execute an action, that requires elevation.

推荐答案

AFAIK,从您似乎想要的意义上说,没有办法做到.即运行指定的 .exe 并期望立即出现提示.

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.

我所做的是针对我知道必须使用管理权限运行的命令,我使用一个名为 Invoke-Admin 的函数来运行它们.它确保我以管理员身份运行,如果我不在运行命令之前,它将用 UAC 对话框提示用户.

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.

在这里

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();
    }
}

这篇关于如果操作需要提升,则在 PowerShell 中显示 UAC 提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆