你知道吗,如果你是一个系统的管理用户,你可以右键单击一个批处理脚本,然后以管理员的身份运行它,而不需要输入管理员密码?
我想知道如何使用PowerShell脚本来做到这一点。我不希望必须输入我的密码;我只想模仿右键单击Run As Administrator方法。
到目前为止,我读到的所有内容都要求您提供管理员密码。
发布于 2012-07-12 04:06:16
以下是对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进程(如果当前用户可以访问管理员模式,并且脚本不是以管理员身份启动的)。
发布于 2015-07-24 12:16:35
自提升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
发布于 2015-01-10 11:49:06
本杰明·阿姆斯特朗发布了一条excellent article about self-elevating PowerShell scripts。他的代码有一些小问题;下面是基于注释中建议的修复的修改版本。
基本上,它获取与当前进程相关联的标识,检查它是否是管理员,如果不是,则创建一个具有管理员权限的新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");
https://stackoverflow.com/questions/7690994
复制相似问题