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

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

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


当前回答

您需要使用管理权限重新运行脚本,并检查脚本是否在该模式下启动。下面我写了一个脚本,它有两个函数: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
}

其他回答

您需要使用管理权限重新运行脚本,并检查脚本是否在该模式下启动。下面我写了一个脚本,它有两个函数: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
}

提升PowerShell from Start>运行

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

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

事实证明这太简单了。您所要做的就是以管理员身份运行cmd。然后输入explorer.exe并按enter键。这会打开Windows资源管理器。 现在右键单击你想要运行的PowerShell脚本,选择“运行PowerShell”,这将在管理员模式下启动PowerShell。

它可能会要求您启用策略以运行,键入Y并按enter。现在脚本将以管理员身份在PowerShell中运行。万一全红了,说明你的政策还没生效。然后再试一次,应该可以正常工作。

您可以创建一个批处理文件(*.bat),在双击时使用管理权限运行powershell脚本。通过这种方式,您不需要更改powershell脚本中的任何内容。要做到这一点,创建一个与powershell脚本名称和位置相同的批处理文件,然后将以下内容放入其中:

@echo off

set scriptFileName=%~n0
set scriptFolderPath=%~dp0
set powershellScriptFileName=%scriptFileName%.ps1

powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"%scriptFolderPath%`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"

就是这样!

下面是解释:

假设powershell脚本位于路径C:\Temp\ScriptTest。ps1,您的批处理文件必须有路径C:\Temp\ScriptTest.bat。当有人执行这个批处理文件时,会发生以下步骤:

The cmd will execute the command powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs" A new powershell session will open and the following command will be executed: Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs Another new powershell session with administrative privileges will open in the system32 folder and the following arguments will be passed to it: -ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\"" The following command will be executed with administrative privileges: cd "C:\Temp"; & ".\ScriptTest.ps1" Once the script path and name arguments are double quoted, they can contain space or single quotation mark characters ('). The current folder will change from system32 to C:\Temp and the script ScriptTest.ps1 will be executed. Once the parameter -NoExit was passed, the window wont be closed, even if your powershell script throws some exception.

这种行为是经过设计的。因为微软真的不想让.ps1文件成为最新的电子邮件病毒,所以有多层安全措施。有些人认为这与任务自动化的概念相悖,这是公平的。Vista+安全模型是“去自动化”的,这样用户就可以接受。

但是,我怀疑如果你启动powershell本身作为提升,它应该能够运行批处理文件,而不需要再次要求密码,直到你关闭powershell。