PowerShell: Running a command as Administrator
You know how if you're the administrative user of a system and you can just right click say, a batch script and run it as Administrator without entering the administrator password?
I'm wondering how to do this with a PowerShell script. I do not want to have to enter my password; I just want to mimic the right-click Run As Administrator method.
Everything I read so far requires you to supply the administrator password.
如果当前的控制台未提升,并且您要执行的操作需要提升的权限,则可以使用“以管理员身份运行”选项启动PowerShell
PS> Start-Process powershell -Verb runAs
Here is an addition to Shay Levi's suggestion (just add these lines at the beginning of a script):
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
}
This results in the current script being passed to a new powershell process in Administrator mode (if current User has access to Administrator mode and the script is not launched as Administrator).
Self elevating PowerShell script
Windows 8.1 / PowerShell 4.0 +
One line :)
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
链接地址: http://www.djcxy.com/p/30240.html