您知道如果您是系统的管理员用户,您可以右键单击一个批处理脚本,然后以管理员身份运行它,而无需输入管理员密码?

我想知道如何用PowerShell脚本做到这一点。我不想输入我的密码;我只是想模仿右键单击Run As Administrator方法。

到目前为止,我读到的所有内容都要求您提供管理员密码。


当前回答

下面是Powershell脚本的自我提升代码片段,它保留了工作目录:

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
    exit;
}

# Your script here

保存工作目录对于执行路径相关操作的脚本很重要。几乎所有其他答案都不保留此路径,这可能会在脚本的其余部分中导致意外错误。

如果您不愿意使用自我提升的脚本/片段,而只是想以管理员身份简单地启动脚本(例如;从浏览器上下文菜单),在这里看到我的另一个答案:https://stackoverflow.com/a/57033941/2441655

其他回答

提升PowerShell from Start>运行

在2012R2或2016年,你不能在没有炮击两次的情况下使用“run”命令运行elevated powershell:

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell -命令"saps powershell -Verb RunAs "

以下是对Shay Levi建议的补充(只需在脚本开头添加这些行):

if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))  
{  
  $arguments = "& '" +$myinvocation.mycommand.definition + "'"
  Start-Process powershell -Verb runAs -ArgumentList $arguments
  Break
}

这将导致当前脚本以管理员模式传递给一个新的powershell进程(如果当前User具有管理员模式,并且脚本不是以管理员身份启动)。

下面是Powershell脚本的自我提升代码片段,它保留了工作目录:

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"";
    exit;
}

# Your script here

保存工作目录对于执行路径相关操作的脚本很重要。几乎所有其他答案都不保留此路径,这可能会在脚本的其余部分中导致意外错误。

如果您不愿意使用自我提升的脚本/片段,而只是想以管理员身份简单地启动脚本(例如;从浏览器上下文菜单),在这里看到我的另一个答案:https://stackoverflow.com/a/57033941/2441655

您需要使用管理权限重新运行脚本,并检查脚本是否在该模式下启动。下面我写了一个脚本,它有两个函数:DoElevatedOperations和DoStandardOperations。您应该将需要管理权限的代码放在第一个中,将标准操作放在第二个中。IsRunAsAdmin变量用于标识管理模式。

我的代码是微软脚本的简化摘录,当你为Windows Store应用程序创建应用程序包时自动生成。

param(
    [switch]$IsRunAsAdmin = $false
)

# Get our script path
$ScriptPath = (Get-Variable MyInvocation).Value.MyCommand.Path

#
# Launches an elevated process running the current script to perform tasks
# that require administrative privileges.  This function waits until the
# elevated process terminates.
#
function LaunchElevated
{
    # Set up command line arguments to the elevated process
    $RelaunchArgs = '-ExecutionPolicy Unrestricted -file "' + $ScriptPath + '" -IsRunAsAdmin'

    # Launch the process and wait for it to finish
    try
    {
        $AdminProcess = Start-Process "$PsHome\PowerShell.exe" -Verb RunAs -ArgumentList $RelaunchArgs -PassThru
    }
    catch
    {
        $Error[0] # Dump details about the last error
        exit 1
    }

    # Wait until the elevated process terminates
    while (!($AdminProcess.HasExited))
    {
        Start-Sleep -Seconds 2
    }
}

function DoElevatedOperations
{
    Write-Host "Do elevated operations"
}

function DoStandardOperations
{
    Write-Host "Do standard operations"

    LaunchElevated
}


#
# Main script entry point
#

if ($IsRunAsAdmin)
{
    DoElevatedOperations
}
else
{
    DoStandardOperations
}

加上我的意见。我的简单版本基于net session,到目前为止一直在Windows 7 / Windows 10中工作。为什么要过于复杂呢?

if (!(net session)) {$path =  "& '" + $myinvocation.mycommand.definition + "'" ; Start-Process powershell -Verb runAs -ArgumentList $path ; exit}

只需添加到脚本顶部,它将以管理员身份运行。