Source/Session/Invoke-SessionElevation.ps1

<#
.SYNOPSIS
    Relaunches the current session with elevated privileges.
.DESCRIPTION
    Checks whether the current session is already elevated via Test-SessionElevation. If not, starts a new process for the given executable with the "RunAs" verb, forwarding the supplied command-line arguments, and exits the current session.
    When the current session is running inside Windows Terminal (detected via the WT_SESSION environment variable) and "wt.exe" is available, the elevated process is launched through Windows Terminal instead.
.PARAMETER FilePath
    The path of the executable to relaunch elevated. Defaults to the executable of the current process.
.PARAMETER ArgumentList
    The command-line parameters and arguments to forward to the elevated process.
.EXAMPLE
    Invoke-SessionElevation
.EXAMPLE
    Invoke-SessionElevation -ArgumentList @("-NoExit", "-File", "C:\Foo\Bar.ps1", "-Baz", "Qux")
.INPUTS
    None.
.OUTPUTS
    None.
#>


function Invoke-SessionElevation {

    [CmdletBinding(SupportsShouldProcess)]

    param(
        [string]
        $FilePath = (Get-Process -Id $PID).Path,

        [string[]]
        $ArgumentList = @()
    )

    if (Test-SessionElevation) {

        return

    }

    $launchPath = $FilePath
    $launchArguments = $ArgumentList

    $windowsTerminal = Get-Command -Name "wt.exe" -ErrorAction "SilentlyContinue"

    if (($null -ne $env:WT_SESSION) -and ($null -ne $windowsTerminal)) {

        $launchPath = $windowsTerminal.Source
        $launchArguments = @("--", $FilePath) + $ArgumentList

    }

    $startProcessParameters = @{
        FilePath = $launchPath
        Verb     = "RunAs"
    }

    if ($launchArguments.Count -gt 0) {

        $startProcessParameters.ArgumentList = $launchArguments

    }

    if ($PSCmdlet.ShouldProcess($launchPath, "Relaunch session elevated")) {

        try {

            Start-Process @startProcessParameters -ErrorAction "Stop"

        } catch {

            Write-Error $_

            return

        }

        exit

    }

}