如何使用powershell脚本请求管理员权限

Est*_*net 6 powershell

如何编写 powershell 脚本来请求用户的管理员权限?打开模式并接受或输入管理员密码。是否可以?

pro*_*365 17

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

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
}
}
Run Code Online (Sandbox Code Playgroud)

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