【发布时间】: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