【问题标题】:Elevate a script with parameters使用参数提升脚本
【发布时间】:2022-01-22 16:18:11
【问题描述】:

我有一个 Powershell 脚本,其中包含我希望能够自我提升的参数。

[CmdletBinding()]
param (
    [Parameter(ParameterSetName="cp")]
    [Switch]
    $copy = $false,
    [Parameter(ParameterSetName="mv")]
    [Switch]
    $move = $false
)
# Elevate if required
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
  if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
    $Cmd = (
      '-File',
      "`"$($MyInvocation.MyCommand.Path)`"",
      $MyInvocation.BoundParameters
    )
    $ProcArgs = @{
      FilePath = 'PowerShell.exe'
      Verb = 'RunAs'
      ArgumentList = $Cmd
    }
    Start-Process @ProcArgs
    Exit
  }
}
Set-Location -LiteralPath $PSScriptRoot
Write-Host "$copy"
Pause

如果我注释掉 param 块并运行 script.ps1 -copy,则会打开一个提升的 Powershell 窗口并打印出 Press enter to continue,即它可以工作。

如果我注释掉if语句,当前窗口输出True,即它也可以工作。

如果我运行整个程序,提升的窗口会打开一瞬间,然后关闭,忽略 Pause,任何地方都没有输出。 我希望提升的窗口打开并打印出True

【问题讨论】:

  • @()sub-expression 运算符,您不一定需要它,因为您在 $cmd 中的参数已经用逗号分隔,但我想我' d 分享;因为您只使用常规的 分组运算符 () 是我提到它的原因。无论如何,您可以尝试添加Start-Transcript 并查看结果。它应该捕获错误消息并将其输出到文件中。
  • 您将 string System.Management.Automation.PSBoundParametersDictionary 作为参数传递,而不是传递实际的开关参数。
  • @AbrahamZinala 我使用(),所以我可以垂直对齐元素。不幸的是,成绩单中没​​有输出。它只显示script.ps1 -copy
  • @SantiagoSquarzon 感谢您的提醒!我已经更新了帖子。不幸的是,这并不能解决问题。

标签: powershell uac


【解决方案1】:

我在 Linux 上对此进行了测试并为我工作,但无法在 Windows 上进行测试,我看不出有其他方法可以将 $PSBoundParameters 操作到 strings 中以在 @ 上传递参数987654323@.

以下代码仅用于测试,因此我删除了if 条件。

[CmdletBinding()]
param (
    [Parameter(ParameterSetName="cp")]
    [Switch]$copy,
    [Parameter(ParameterSetName="mv")]
    [Switch]$move
)

$argument = @(
    "-File $PSCommandPath"    
    "-$($PSBoundParameters.Keys)"
)

$ProcArgs = @{
    FilePath = 'powershell.exe'
    Verb = 'RunAs'
    ArgumentList = $argument
}

Start-Process @ProcArgs

"Started new Process with the argument: -$($PSBoundParameters.Keys)"
[System.Console]::ReadKey()
Exit

【讨论】:

  • 这会在Start-Process @ProcArgsi.imgur.com/bOr9SWD.png 行抛出Start-Process : This command cannot be run due to the error: The system cannot find the file specified
  • @stackexchange_account1111 对,我忘了把pwsh改成powershell.exe我的错
  • 成功了!它无限期地不断创建新的提升窗口,但是在我放回 if 语句后,它成功创建了一个提升窗口并传递了参数。非常感谢。
  • @stackexchange_account1111 没错,脚本正在递归调用自己,应该提到抱歉,哈哈!乐于助人:)
猜你喜欢
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-06-22
  • 2022-10-25
相关资源
最近更新 更多