您知道如果您是系统的管理员用户,您可以右键单击一个批处理脚本,然后以管理员身份运行它,而无需输入管理员密码?
我想知道如何用PowerShell脚本做到这一点。我不想输入我的密码;我只是想模仿右键单击Run As Administrator方法。
到目前为止,我读到的所有内容都要求您提供管理员密码。
您知道如果您是系统的管理员用户,您可以右键单击一个批处理脚本,然后以管理员身份运行它,而无需输入管理员密码?
我想知道如何用PowerShell脚本做到这一点。我不想输入我的密码;我只是想模仿右键单击Run As Administrator方法。
到目前为止,我读到的所有内容都要求您提供管理员密码。
当前回答
我找到了一个方法…
创建一个批处理文件打开你的脚本:
@echo off
START "" "C:\Scripts\ScriptName.ps1"
然后创建一个快捷方式,在桌面上说(右键单击新建->快捷方式)。
然后粘贴到位置:
C:\Windows\System32\runas.exe /savecred /user:*DOMAIN*\*ADMIN USERNAME* C:\Scripts\BatchFileName.bat
第一次打开时,您必须输入一次密码。然后将其保存在Windows凭据管理器中。
在此之后,您应该能够以管理员身份运行,而无需输入管理员用户名或密码。
其他回答
在Shay Levy的答案之上,遵循下面的设置(只有一次)
以管理员权限启动PowerShell。 在堆栈溢出问题PowerShell说“脚本的执行在这个系统上是禁用的。” 例如,将.ps1文件放在任何PATH文件夹中。Windows \ System32系统文件夹
设置之后:
按Win + R 调用powershell Start-Process powershell -Verb runAs <ps1_file>
现在,您可以在一个命令行中运行所有内容。上述操作适用于Windows 8 Basic 64位。
提升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具有管理员模式,并且脚本不是以管理员身份启动)。
要将命令的输出附加到包含当前日期的文本文件名,可以这样做:
$winupdfile = 'Windows-Update-' + $(get-date -f MM-dd-yyyy) + '.txt'
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`"" -Verb RunAs; exit } else { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"Get-WUInstall -AcceptAll | Out-File $env:USERPROFILE\$winupdfile -Append`""; exit }
我还没见过自己的方法,所以,试试这个。它更容易遵循,占用的空间也更小:
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)非常流行的方法的变体,即如何在不真正掌握实际操作的情况下完成它,以及如何模仿相同的程序。