首页/系统/Windows 运维速查/脚本自提权(检测并 RunAs 重启自身)
本包目录(413 条)

脚本自提权(检测并 RunAs 重启自身)

PowerShell 脚本需要管理员:先检测当前令牌,不是管理员就用 RunAs 重启自身,再退出原进程。

Windows 运维速查系统更新于 2026-10-12
用途让脚本以管理员权限继续执行
核心WindowsPrincipal.IsInRole 判定 + Start-Process -Verb RunAs
无人值守改用计划任务“使用最高权限运行”

常用示例

常用示例
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
  Start-Process powershell -Verb RunAs -ArgumentList '-NoProfile','-File',"`"$PSCommandPath`""
  exit
}
Write-Host '已以管理员身份运行'
自提权会弹 UAC 确认;无人值守场景计划任务直接勾选最高权限更可靠。

易错点

  • RunAs 是全新进程:原进程的工作目录、变量、映射盘都不会带过去
  • Server Core 或无交互会话下自提权会失败,需要其他提权路径

数据来源与参考

  • Microsoft Learn:Start-Process
  • Microsoft Learn:WindowsPrincipal.IsInRole

相关工具

​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌