You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让PowerShell脚本自提升 运行前提示用户输入高权限凭证

PowerShell脚本提权实现方案

代码添加位置

权限提升代码需要放在脚本最开头,早于所有原有业务逻辑(包括你原脚本开头的Clear-Host),确保脚本执行任何操作前先完成权限校验和提权。

具体实现代码

将以下代码粘贴到脚本最开头即可:

# 校验当前运行身份是否为管理员
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$isAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

# 非管理员身份时触发UAC提权弹窗,要求输入高权限凭证
if (-not $isAdmin) {
    # 以管理员身份重新启动当前脚本
    Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$($MyInvocation.MyCommand.Path)`"" -Verb RunAs
    # 退出当前低权限进程,避免后续逻辑重复执行
    Exit
}

实现逻辑说明

  • 脚本运行时首先校验当前用户的权限等级,已经是管理员身份的话直接运行原有业务代码
  • 非管理员身份会自动触发系统UAC提权弹窗,用户输入高权限账号密码并确认后,会启动新的高权限PowerShell进程执行完整脚本
  • 若用户在UAC弹窗点击取消,脚本直接退出,不会执行后续操作

改后完整脚本示例

# 校验当前运行身份是否为管理员
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$isAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

# 非管理员身份时触发UAC提权弹窗,要求输入高权限凭证
if (-not $isAdmin) {
    # 以管理员身份重新启动当前脚本
    Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$($MyInvocation.MyCommand.Path)`"" -Verb RunAs
    # 退出当前低权限进程,避免后续逻辑重复执行
    Exit
}

Clear-Host
#Variable for where the E-Billing files are downloaded
$FilePath = "\\LNAPPS\APPS\Finance\eBilling Hub Workstation Configuration\eBillingHub\utils"

#Test if the path exists
$TestPath = Test-Path $FilePath

#If $filepath exists, execute the following files
if ($TestPath -eq $true) 
{
    Write-Host "Path exists" -ForegroundColor Green
    Start-Process -FilePath "$FilePath\addper.bat"
    Start-Process -FilePath "$FilePath\AddToTrustedSites.reg" 
    Start-Process -FilePath "$FilePath\DotNetPermissions.reg"
}
#If path doesn't exist, write error message
Else
{
    Write-Host "Path not found" | Write-Error
    Exit
}

Write-Host "Configuration complete" -ForegroundColor Blue

可选优化

如果你需要静默导入注册表文件、不弹出用户确认提示,可以将注册表执行的代码调整为:

Start-Process reg.exe -ArgumentList "import `"$FilePath\AddToTrustedSites.reg`"" -Wait -NoNewWindow
Start-Process reg.exe -ArgumentList "import `"$FilePath\DotNetPermissions.reg`"" -Wait -NoNewWindow

内容的提问来源于stack exchange,提问作者Khalifa96

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:36:03