如何让带参数的PowerShell脚本以管理员权限重启并保留参数
解决PowerShell脚本提权后丢失参数的问题
原来的提权代码用$PSCommandArgs传递参数时,没法正确处理带空格的字符串参数和开关参数的格式,导致提权后参数丢失。下面是修复后的代码,能完整保留所有参数:
# 检查是否以管理员身份运行 $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { # 构建要传递的参数数组 $arguments = @() # 添加脚本路径 $arguments += "-File `"$PSCommandPath`"" # 处理开关参数(仅传递非默认值,因为默认值是$true) if (-not $SkipUpdate) { $arguments += "-SkipUpdate:`$false" } if (-not $UserReport) { $arguments += "-UserReport:`$false" } if (-not $ComputerReport) { $arguments += "-ComputerReport:`$false" } # 处理字符串参数(非空时传递,带空格自动用引号包裹) if ($SearchScope -ne "") { $arguments += "-SearchScope `"$SearchScope`"" } # 启动管理员权限的PowerShell进程 Start-Process powershell.exe -ArgumentList $arguments -Verb RunAs exit } # 下面是你的脚本主体逻辑示例 Write-Host "已以管理员身份运行,当前参数:" Write-Host "SkipUpdate: $SkipUpdate" Write-Host "UserReport: $UserReport" Write-Host "ComputerReport: $ComputerReport" Write-Host "SearchScope: $SearchScope"
关键说明
- 手动构建参数数组比直接拼接字符串更可靠,能避免转义错误
- 开关参数只传递非默认值(比如默认是
$true,只有设为$false时才需要显式传递-参数名:$false) - 字符串参数用双引号包裹,确保带空格的内容能被正确解析
完整脚本示例
把提权逻辑放在参数定义之后、脚本主体之前:
Param ( [Parameter(Mandatory = $false)][switch]$SkipUpdate = $true, [Parameter(Mandatory = $false)][switch]$UserReport = $true, [Parameter(Mandatory = $false)][switch]$ComputerReport = $true, [Parameter(Mandatory = $false)][string]$SearchScope = "" ) # 提权检查与重启逻辑 $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { $arguments = @() $arguments += "-File `"$PSCommandPath`"" if (-not $SkipUpdate) { $arguments += "-SkipUpdate:`$false" } if (-not $UserReport) { $arguments += "-UserReport:`$false" } if (-not $ComputerReport) { $arguments += "-ComputerReport:`$false" } if ($SearchScope -ne "") { $arguments += "-SearchScope `"$SearchScope`"" } Start-Process powershell.exe -ArgumentList $arguments -Verb RunAs exit } # 脚本功能代码写在这里
内容的提问来源于stack exchange,提问作者Cool34
相关产品推荐
相关产品推荐

