如何在PowerShell中使用/不使用提升权限运行exe

时间:2015-03-25 21:12:36

标签: powershell admin uac

我想要一种简单的方法来运行具有来自同一用户的不同权限的进程,而无需询问或了解他/她的密码。如有必要,可以使用对话框。我宁愿不启动PowerShell子流程来实现这一目标。

场景1: PowerShell脚本以管理模式运行。我想在没有管理员权限但是在同一个用户上启动脚本或.exe。

场景2: PowerShell脚本正常运行。我想在同一个用户上启动一个具有管理员权限的脚本或.exe。

2 个答案:

答案 0 :(得分:5)

我们将其分为三个部分。

首先确定当前会话是否以管理员权限运行:

$CurrentID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$CurrentPrincipal = new-object System.Security.Principal.WindowsPrincipal($CurrentID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator

# Check to see if session is currently with admin privileges

if ($CurrentPrincipal.IsInRole($adminRole)) {
    write-host "Yes we are running elevated."
}else{
    write-host "No this is a normal user session."
}

现在,如果我们使用或不使用提升运行,您可以使用提升的权限启动新进程,如下所示:

$newProc = new-object System.Diagnostics.ProcessStartInfo "PowerShell"
# Specify what to run
$newProc.Arguments = "powershell.exe"
# If you set this, process will be elevated
$newProc.Verb = "runas"
[System.Diagnostics.Process]::Start($newProc)

最后,如果我们拥有提升的权限,但又希望在没有...

的情况下启动新流程

我不知道。将不得不试图找到答案,但由于这不是一个常见的情况,我到目前为止没有运气。

编辑:我现在已经看到了针对此方案的几个“解决方案”。在.NET / PowerShell中没有本地方法可以执行此操作。有些非常复杂(调用12个COM对象)。这个vista-7-uac-how-to-lower-process-privileges是一个很好的参考。

对我来说似乎最优雅的是利用explorer.exe中的“bug”。 只需使用explorer.exe启动.exe,生成的进程将再次运行而不会提升权限。

$newProc = new-object System.Diagnostics.ProcessStartInfo "PowerShell"
# Specify what to run, you need the full path after explorer.exe
$newProc.Arguments = "explorer.exe C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
[System.Diagnostics.Process]::Start($newProc)

编辑#2:我刚刚发现从 开始新的 非提升 流程的另一种方法已升级的 环境是使用runas.exe与0x20000(基本用户)信任级别:

C:\> runas /showtrustlevels The following trust levels are available on your system: 0x20000 (Basic User) C:\> runas /trustlevel:0x20000 devenv

enter image description here

答案 1 :(得分:0)

在需要提升模式的所有脚本中,我将其用作第一条命令,如果我忘记以管理员身份启动,它将把脚本转移到另一个提升的进程中。您必须确认,因此它不适合自动化任务

Unable to load asset: assets/file.js