强制PowerShell脚本以管理员权限运行 7


背景

我给别人写了一个PowerShell脚本,让他运行时一定要以管理员权限运行,可是说的再清楚,他也有忘得时候。甚至有的朋友刚从XP步入Windows 7 或者 Windows 8的殿堂,对于UAC不是很清楚,更别提以管理员权限运行了。然后出错了,又来问我,他烦我也烦。

我不怪他们,我只恨我自己,我恨我自己左手一只鸡,右手一只鸭,只把“为人民服务”当作口号,挂在嘴皮子上了,从来都没有及群众之所急。我当初如果在我的脚本前面多加几行下面的代码,要节省下多少维稳经费啊。

知识点

  • 自动检测当前控制台是否是以管理员权限打开,如果不是,重新打开新的控制台运行当前脚本。
  • 将绑定的参数BoundParameters和非绑定的参数$args,发送给新的控制台。

脚本

param( $a, $b ) 
#region 关键代码:强迫以管理员权限运行
$currentWi = [Security.Principal.WindowsIdentity]::GetCurrent() 
$currentWp = [Security.Principal.WindowsPrincipal]$currentWi 

if( -not $currentWp.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) 
{ 
  $boundPara = ($MyInvocation.BoundParameters.Keys | foreach{
     '-{0} {1}' -f  $_ ,$MyInvocation.BoundParameters[$_]} ) -join ' '
  $currentFile = (Resolve-Path  $MyInvocation.InvocationName).Path 

 $fullPara = $boundPara + ' ' + $args -join ' '
 Start-Process "$psHome\powershell.exe"   -ArgumentList "$currentFile $fullPara"   -verb runas 
 return
} 
#endregion

#region 测试脚本片段
"a=$a, b=$b"
 ($args -join ' ')
Write-Host  '执行完毕,按任意键退出...'
Read-Host
#endregion

运行结果

PS> .\test.ps1 -a 8 -b 9 66 77 88 99

a=8, b=9
66 77 88 99
执行完毕,按任意键退出...

PS>
本文链接: https://www.pstips.net/force-script-run-as-admin.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

7 条评论 “强制PowerShell脚本以管理员权限运行