PowerShell:以管理员身份运行命令

chr*_*ips 246 powershell administrator

您知道如果您是系统的管理用户,您可以右键单击"说",批处理脚本并以管理员身份运行它而不输入管理员密码吗?

我想知道如何使用PowerShell脚本执行此操作.我不想输入密码; 我只是想模仿右键单击Run As Administrator方法.

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

Sha*_*evy 272

如果当前控制台未升级并且您尝试执行的操作需要提升权限,则可以使用"以管理员身份运行"选项启动PowerShell

PS> Start-Process powershell -Verb runAs
Run Code Online (Sandbox Code Playgroud)

  • 这将在不同的位置打开一个新的控制台.有没有办法在当前工作目录中以管理员身份运行? (13认同)
  • `start-process -verb runAs"<cmd>" - argumentlist"<args1> <args2>"`;) (7认同)
  • 在“CMD”窗口中,最短的版本是:“powershell start cmd -v runas”。要验证新获得的权限,请运行:“net sess”。 (4认同)
  • 备注:简短版本只能通过打字使用。在脚本中,出于可读性原因,您应该使用完整长度。 (4认同)
  • `Start-Process wt -Verb runAs` 用于以管理员身份启动 Windows 终端 (2认同)

小智 105

这是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
}
Run Code Online (Sandbox Code Playgroud)

这会导致当前脚本以管理员模式传递给新的PowerShell进程(如果当前用户可以访问管理员模式,并且脚本未以管理员身份启动).

  • 这对我有用:`if(-not(([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity] :: GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] :: Administrator)))` (6认同)
  • @ G.Lombard的评论有一个微妙的语法错误.这对我有用:```if(-not([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity] :: GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] :: Administrator)) ``` (2认同)

Jay*_*end 92

自升式PowerShell脚本

Windows 8.1/PowerShell 4.0 +

一条线 :)

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }

# Your script here
Run Code Online (Sandbox Code Playgroud)

  • 好吧,从技术上讲,如果格式化的话,一切都是"一行",但这并不能使它成为"一线" (115认同)
  • 缺点:如果在提示中输入非管理员用户,则将导致无休止的fork-exit循环。 (3认同)
  • 但这并没有通过args (3认同)
  • 这也适用于Windows 10 Pro.谢谢. (2认同)
  • 为了传递参数,我将其修改为:`if(!([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity] :: GetCurrent())。IsInRole([Security.Principal.WindowsBuiltInRole]“ Administrator”){启动过程powershell.exe“ -NoProfile -ExecutionPolicy绕过-文件\`” $ PSCommandPath \`“ \`” $ args \`“”-动词RunAs; 退出}` (2认同)
  • 此答案不会保留工作目录。看到这里做的一个:stackoverflow.com/a/57035712/2441655 (2认同)

And*_*dri 43

Benjamin Armstrong发表了一篇关于自我提升PowerShell脚本优秀文章.他的代码有一些小问题; 基于修订建议的修改版本如下所示.

基本上,它获取与当前进程关联的标识,检查它是否是管理员,如果不是,则创建具有管理员权限的新PowerShell进程并终止旧进程.

# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);

# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;

# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
    # We are running as an administrator, so change the title and background colour to indicate this
    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
    $Host.UI.RawUI.BackgroundColor = "DarkBlue";
    Clear-Host;
}
else {
    # We are not running as an administrator, so relaunch as administrator

    # Create a new process object that starts PowerShell
    $newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";

    # Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path
    $newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"

    # Indicate that the process should be elevated
    $newProcess.Verb = "runas";

    # Start the new process
    [System.Diagnostics.Process]::Start($newProcess);

    # Exit from the current, unelevated, process
    Exit;
}

# Run your code that needs to be elevated here...

Write-Host -NoNewLine "Press any key to continue...";
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
Run Code Online (Sandbox Code Playgroud)

  • 这个答案不保留工作目录。请参阅此处的一个:stackoverflow.com/a/57035712/2441655 (2认同)

Ros*_*res 18

您可以创建一个批处理文件(*.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"
Run Code Online (Sandbox Code Playgroud)

而已!

这是解释:

假设您的powershell脚本位于路径中C:\Temp\ScriptTest.ps1,您的批处理文件必须具有该路径C:\Temp\ScriptTest.bat.当有人执行此批处理文件时,将执行以下步骤:

  1. cmd将执行该命令

    powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoProfile -NoExit -Command `\"cd \`\"C:\Temp\`\"; & \`\".\ScriptTest.ps1\`\"`\"\" -Verb RunAs"
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将打开一个新的PowerShell会话,并执行以下命令:

    Start-Process powershell "-ExecutionPolicy Bypass -NoProfile -NoExit -Command `"cd \`"C:\Temp\`"; & \`".\ScriptTest.ps1\`"`"" -Verb RunAs
    
    Run Code Online (Sandbox Code Playgroud)
  3. 另一个具有管理权限的新PowerShell会话将在system32文件夹中打开,并且以下参数将传递给它:

    -ExecutionPolicy Bypass -NoProfile -NoExit -Command "cd \"C:\Temp\"; & \".\ScriptTest.ps1\""
    
    Run Code Online (Sandbox Code Playgroud)
  4. 将使用管理权限执行以下命令:

    cd "C:\Temp"; & ".\ScriptTest.ps1"
    
    Run Code Online (Sandbox Code Playgroud)

    一旦脚本路径和名称参数被双引号,它们可以包含空格或单引号字符(').

  5. 当前文件夹将从更改system32C:\Temp,脚本ScriptTest.ps1将被执行.一旦参数-NoExit传递,即使你的powershell脚本抛出一些异常,窗口也不会被关闭.

  • @JohnSlegers,如果您需要自动化,您有责任确保以管理员身份运行自动化流程。如果您可以在没有用户交互的情况下自动将非管理员进程提升为管理员进程,那么首先要求进程具有管理员权限的目的将落空。 (2认同)
  • FWIW,@mems 编辑#5 对我来说是错误的。在 `%scriptFolderPath%` 之后添加的反斜杠给我带来了错误。 (2认同)

man*_*lds 14

您可以轻松添加一些注册表项以获取文件的"以管理员身份运行"上下文菜单.ps1:

New-Item -Path "Registry::HKEY_CLASSES_ROOT\Microsoft.PowershellScript.1\Shell\runas\command" `
-Force -Name '' -Value '"c:\windows\system32\windowspowershell\v1.0\powershell.exe" -noexit "%1"'
Run Code Online (Sandbox Code Playgroud)

(从@Shay更新为更简单的脚本)

基本上在HKCR:\Microsoft.PowershellScript.1\Shell\runas\command设置默认值时使用Powershell调用脚本.


aka*_*ppi 13

运用

#Requires -RunAsAdministrator

尚未说明.它似乎只有自PowerShell 4.0以来.

http://technet.microsoft.com/en-us/library/hh847765.aspx

将此switch参数添加到requires语句时,它指定必须使用提升的用户权限(以管理员身份运行)启动运行该脚本的Windows PowerShell会话.

对我而言,这似乎是一个很好的方法,但我不确定现场经验.PowerShell 3.0运行时可能会忽略这一点,甚至更糟糕的是,会出错.

当脚本以非管理员身份运行时,会出现以下错误:

无法运行脚本'StackOverflow.ps1',因为它包含以管理员身份运行的"#requires"语句.当前的Windows PowerShell会话未以管理员身份运行.使用"以管理员身份运行"选项启动Windows PowerShell,然后再次尝试运行该脚本.

+ CategoryInfo          : PermissionDenied: (StackOverflow.ps1:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ScriptRequiresElevation
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,如果shell没有管理员权限,它所做的就是使脚本失败并显示错误.它本身并没有提升. (6认同)
  • 而且它会使脚本在PowerShell 2.0上失败。真是愚蠢。我从来没有结束使用它。这不好。他们在想什么? (2认同)

Joh*_*ohn 10

Jonathan和Shay Levy发布的代码对我不起作用.

请在下面找到工作代码:

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{   
#"No Administrative rights, it will display a popup window asking user for Admin rights"

$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments

break
}
#"After user clicked Yes on the popup, your file will be reopened with Admin rights"
#"Put your code here"
Run Code Online (Sandbox Code Playgroud)

  • @Abatonime你怎么能指出容易错过差异而不是为了读者的利益?老实说,这个变化不仅仅是对另一个答案的评论. (3认同)
  • 非常有用和实用的解决方案:只是将它扩展到我的脚本并且它可以工作. (2认同)

Ryt*_*hon 8

您需要使用管理权限重新运行脚本,并检查脚本是否以该模式启动.下面我编写了一个脚本,它有两个函数:DoElevatedOperationsDoStandardOperations.您应该将需要管理员权限的代码放入第一个,将标准操作放入第二个.所述IsRunAsAdmin变量用来识别管理模式.

我的代码是Microsoft脚本的简化摘录,在您为Windows应用商店应用创建应用包时自动生成.

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
}
Run Code Online (Sandbox Code Playgroud)


Ven*_*ryx 8

这是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
Run Code Online (Sandbox Code Playgroud)

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

如果您不想使用自动提升的脚本/代码段,而只想以一种简单的方式以管理员身份启动脚本(例如,从资源管理器上下文菜单中),请在此处查看我的其他答案:https:// stackoverflow .com / a / 57033941/2441655


Rak*_*kha 7

再加上我的2美分。我基于网络会话的简单版本至今在Windows 7 / Windows 10中一直有效。为什么过于复杂?

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

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


rap*_*hie 6

当然,如果您有管理员帐户,也可以强制应用程序以管理员身份打开。

在此处输入图片说明

找到文件,右键单击>属性>快捷方式>高级,然后选中以管理员身份运行

然后单击“确定”。

  • 你如何编写这个脚本? (3认同)

Dis*_*ned 6

这里的许多答案都很接近,但比需要的工作多了一点。

创建脚本的快捷方式并将其配置为“以管理员身份运行”:

  • 创建快捷方式。
  • 右键单击快捷方式并打开Properties...
  • 编辑Target<script-path>powershell <script-path>
  • 单击Advanced...并启用Run as administrator


Voi*_*tar 5

此行为是设计使然。由于 Microsoft 确实不希望 .ps1 文件成为最新的电子邮件病毒,因此存在多层安全性。有些人发现这与任务自动化的概念背道而驰,这是公平的。Vista+ 安全模型是“去自动化”事物,从而让用户接受它们。

但是,我怀疑如果您以提升的身份启动 powershell,它应该能够运行批处理文件而无需再次请求密码,直到您关闭 powershell。


har*_*eep 5

以下是如何运行提升的 powershell 命令并在单个命令中收集 Windows 批处理文件中的输出形式(即不编写 ps1 powershell 脚本)。

powershell -Command 'Start-Process powershell -ArgumentList "-Command (Get-Process postgres | Select-Object Path | Select-Object -Index 0).Path | Out-File -encoding ASCII $env:TEMP\camp-postgres.tmp" -Verb RunAs'
Run Code Online (Sandbox Code Playgroud)

在上面您可以看到我首先使用提升的提示符启动一个 powershell,然后要求启动另一个 powershell(子 shell)来运行该命令。