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

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

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


当前回答

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

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

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

其他回答

在Shay Levy的答案之上,遵循下面的设置(只有一次)

以管理员权限启动PowerShell。 在堆栈溢出问题PowerShell说“脚本的执行在这个系统上是禁用的。” 例如,将.ps1文件放在任何PATH文件夹中。Windows \ System32系统文件夹

设置之后:

按Win + R 调用powershell Start-Process powershell -Verb runAs <ps1_file>

现在,您可以在一个命令行中运行所有内容。上述操作适用于Windows 8 Basic 64位。

乔纳森和谢伊·列维发布的代码对我不起作用。

请在下面找到工作代码:

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"

我发现最可靠的方法是将其包装在一个自动提升的。bat文件中:

@echo off
NET SESSION 1>NUL 2>NUL
IF %ERRORLEVEL% EQU 0 GOTO ADMINTASKS
CD %~dp0
MSHTA "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 0); close();"
EXIT

:ADMINTASKS

powershell -file "c:\users\joecoder\scripts\admin_tasks.ps1"

EXIT

.bat检查您是否已经是管理员,并在需要时以管理员身份重新启动脚本。它还防止多余的“cmd”窗口打开ShellExecute()的第4个参数设置为0。

我还没见过自己的方法,所以,试试这个。它更容易遵循,占用的空间也更小:

if([bool]([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -notcontains "S-1-5-32-544") {
    Start Powershell -ArgumentList "& '$MyInvocation.MyCommand.Path'" -Verb runas
    }

很简单,如果使用管理员权限调用当前Powershell会话,那么在获取当前标识时,管理员组已知SID将显示在组中。即使帐户是该组的成员,SID也不会显示,除非使用提升的凭据调用流程。

几乎所有这些答案都是微软本·阿姆斯特朗(Ben Armstrong)非常流行的方法的变体,即如何在不真正掌握实际操作的情况下完成它,以及如何模仿相同的程序。

这里有一些答案是接近的,但比所需的工作多了一些。

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

创建快捷方式。 右键单击快捷方式并打开属性… 编辑目标从<script-path>到powershell <script-path> 单击高级…并启用以管理员身份运行