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

如何在以管理员身份重启PowerShell脚本时传递所有原参数?

解决PowerShell脚本提权时的通用参数传递问题

你的脚本当前能检测管理员权限并重启进程,但无法传递所有调用时传入的参数。以下是修改后的脚本,实现通用的参数传递逻辑,支持所有命名参数和位置参数:

[CmdletBinding()]
param (
    $Test1
)

# 检测当前是否为管理员身份
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID)
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator

if (-not $myWindowsPrincipal.IsInRole($adminRole)) {
    # 构建命名参数的命令行字符串
    $paramString = $PSBoundParameters.GetEnumerator() | ForEach-Object {
        if ($_.Value -is [string] -and $_.Value.Contains(' ')) {
            "-$($_.Key) `"$($_.Value)`""
        } else {
            "-$($_.Key) $($_.Value)"
        }
    } -join ' '

    # 追加位置参数(如果存在)
    if ($args.Count -gt 0) {
        $paramString += ' ' + ($args | ForEach-Object {
            if ($_ -is [string] -and $_.Contains(' ')) {
                "`"$_`""
            } else {
                "$_"
            }
        } -join ' ')
    }

    # 选择对应的PowerShell可执行文件
    $shellExe = if ($PSVersionTable.PSVersion.Major -eq 5) { 'PowerShell' } else { 'pwsh' }
    
    # 启动管理员权限的进程,传递完整参数
    Start-Process $shellExe -Verb RunAs -ArgumentList @(
        '-NoProfile',
        '-ExecutionPolicy', 'Bypass',
        '-Command', "Set-Location -Path '$pwd'; & '$PSCommandPath' $paramString"
    )
    exit
}

# 提权后的执行逻辑
Write-Host "Test1参数值:$Test1"
Write-Host "已以管理员身份运行"
Write-Host "当前工作目录:$(Get-Item -Path .\).FullName"
Start-Sleep -Seconds 10

关键改进点:

  • 通用参数处理:通过$PSBoundParameters遍历所有命名参数,$args处理位置参数,确保所有传入的参数都能被传递。
  • 空格兼容:对包含空格的字符串参数自动添加引号,避免命令行解析错误。
  • 可靠的参数传递:使用-ArgumentList数组传递启动参数,减少字符串转义带来的问题,比直接拼接命令字符串更稳定。

测试验证:

执行以下命令调用脚本,提权后的窗口会正确显示所有参数:

PS C:\> & .\test.ps1 -Test1 'SampleScript' -OtherParam '参数含空格' 12345

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 07:33:17