您知道如果您是系统的管理员用户,您可以右键单击一个批处理脚本,然后以管理员身份运行它,而无需输入管理员密码?
我想知道如何用PowerShell脚本做到这一点。我不想输入我的密码;我只是想模仿右键单击Run As Administrator方法。
到目前为止,我读到的所有内容都要求您提供管理员密码。
您知道如果您是系统的管理员用户,您可以右键单击一个批处理脚本,然后以管理员身份运行它,而无需输入管理员密码?
我想知道如何用PowerShell脚本做到这一点。我不想输入我的密码;我只是想模仿右键单击Run As Administrator方法。
到目前为止,我读到的所有内容都要求您提供管理员密码。
当前回答
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");
其他回答
您需要使用管理权限重新运行脚本,并检查脚本是否在该模式下启动。下面我写了一个脚本,它有两个函数: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
}
我最近需要在ansible上建立一个环境。我说马上——决定权不在我,但我不记得是从哪里得到的。是这样的:
powershell.exe -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -Command Get-Service -Name ssh-agent | Set-Service -StartupType Automatic' -Verb RunAs}";
本示例启用ssh-agent自动启动。 所需的命令在-Command后指定。唯一的问题是启动发生在一个新的PS实例上,但到目前为止,这是我所知道的以管理员身份执行命令而不需要额外步骤的唯一方法。
你可以很容易地添加一些注册表项来为.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脚本
视窗 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