【问题标题】:Showing the UAC prompt in PowerShell if the action requires elevation如果操作需要提升,则在 PowerShell 中显示 UAC 提示
【发布时间】:2010-12-06 17:19:10
【问题描述】:

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

$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 版本)上,我收到以下错误:

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

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

【问题讨论】:

    标签: powershell uac


    【解决方案1】:

    首先通过Chocolatey安装PowerShell Community Extensionschoco install pscx(你可能需要重启你的shell环境)

    然后启用 pscx

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

    然后使用Invoke-Elevated,例如

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

    【讨论】:

    • 你到底是在哪里找到“Invoke-Elevated”的。除非这是您编写的函数,否则没有这样的命令。我错了吗?
    • 您是否安装并启用了 PSCX?这是 PSCX 的一部分,请参阅 stackoverflow.com/a/8703862/1689770
    • 谢谢,只需输入 Install-Package -Name pscx -Source psgallery 即可!如果它不启动不同的控制台但提升当前控制台会更好,无论如何我认为这取决于Windows如何管理进程......
    【解决方案2】:

    此脚本部分检查中等强制级别令牌(非提升的管理员)并重新启动提升的脚本。

    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
    }
    

    【讨论】:

    • $myGroups 来自哪里?
    【解决方案3】:

    AFAIK,按照您似乎想要的方式,没有办法做到这一点。即运行指定的 .exe 并期望立即出现提示。

    我所做的是对于我知道必须使用管理权限运行的命令,我使用我已经放置的称为 Invoke-Admin 的功能来运行它们。它确保我以管理员身份运行,如果我不是在运行命令之前,它将通过 UAC 对话框提示用户。

    在这里

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

    【讨论】:

    • 对,如何将标准输出和错误输出放入当前命令提示符flux中?
    • pscx 中有这样的东西吗?如果没有,可以添加吗?
    猜你喜欢
    • 2010-10-29
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 2011-05-19
    相关资源
    最近更新 更多