您知道如果您是系统的管理员用户,您可以右键单击一个批处理脚本,然后以管理员身份运行它,而无需输入管理员密码?
我想知道如何用PowerShell脚本做到这一点。我不想输入我的密码;我只是想模仿右键单击Run As Administrator方法。
到目前为止,我读到的所有内容都要求您提供管理员密码。
您知道如果您是系统的管理员用户,您可以右键单击一个批处理脚本,然后以管理员身份运行它,而无需输入管理员密码?
我想知道如何用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}
只需添加到脚本顶部,它将以管理员身份运行。
其他回答
你可以很容易地添加一些注册表项来为.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"'
(从@Shay更新为一个更简单的脚本)
基本上在HKCR:\Microsoft.PowershellScript。1\Shell\runas\命令设置默认值,使用Powershell调用脚本。
这里有一些答案是接近的,但比所需的工作多了一些。
为脚本创建一个快捷方式,并将其配置为“以管理员身份运行”:
创建快捷方式。 右键单击快捷方式并打开属性… 编辑目标从<script-path>到powershell <script-path> 单击高级…并启用以管理员身份运行
提升PowerShell from Start>运行
在2012R2或2016年,你不能在没有炮击两次的情况下使用“run”命令运行elevated powershell:
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell -命令"saps powershell -Verb RunAs "
自提升PowerShell脚本
视窗 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
我发现最可靠的方法是将其包装在一个自动提升的。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。