首页 > 解决方案 > 如何powershell脚本要求管理员权限

问题描述

如何执行 powershell 脚本来向用户请求管理员权限?打开模式并接受或输入管理员密码。可能吗?

标签: powershell

解决方案


我写了一个小片段,将它添加到脚本的开头。

if(!([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
 Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList "-File `"$($MyInvocation.MyCommand.Path)`"  `"$($MyInvocation.MyCommand.UnboundArguments)`""
 Exit
}
}

这将检查脚本是否具有提升的权限,如果没有,将显示 UAC 对话框(如果启用了安全桌面,则为模式对话框)以要求管理员凭据自动提升。


推荐阅读