I have a Powershell script with parameters that I'd like to be able to self-elevate.
[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
If I comment out the param block and run script.ps1 -copy, an elevated Powershell window opens and prints out Press enter to continue, i.e. it works.
If I comment out the if statement, the current window outputs True, i.e. it also works.
If I run the whole thing though, the elevated windows opens for a split second, then closes ignoring Pause with no output anywhere.
I want the elevated window to open and print out True.
@()is the sub-expression operator, which you don't necessarily need since your arguments in$cmdare already comma separated, but I thought I'd share; because you're using just the regular grouping operator()is why I mention it. Anyways, you can try adding aStart-Transcriptand seeing the results. It should capture the error message and output it to a file.System.Management.Automation.PSBoundParametersDictionaryas argument instead of passing the actual switch parameter.()so I could align the elements vertically. No output in transcript, unfortunately. It just showsscript.ps1 -copy