我有一個 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。
uj5u.com熱心網友回復:
我在 Linux 上對此進行了測驗并為我作業,但無法在 Windows 上進行測驗,我認為沒有其他方法必須操作$PSBoundParametersinto字串以在-ArgumentList.
下面的代碼專門用于測驗,因此我洗掉了這些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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389637.html
