Start-ElevatedSession.ps1


<#PSScriptInfo
 
    .VERSION 1.1.0
 
    .GUID 0996e23f-ab0c-4825-afd6-02d19b1e5ab5
 
    .AUTHOR G. Dees
 
    .COMPANYNAME
 
    .COPYRIGHT
 
    .TAGS su sudo
 
    .LICENSEURI
 
    .PROJECTURI
 
    .ICONURI
 
    .EXTERNALMODULEDEPENDENCIES
 
    .REQUIREDSCRIPTS
 
    .EXTERNALSCRIPTDEPENDENCIES
 
    .RELEASENOTES
        1.1.0 - Added Parameter Sets
                Changed hard coded FilePath
 
        1.0.0 - Initial release
 
    .PRIVATEDATA
 
#>


# function Start-ElevatedSession {

    <#
        .SYNOPSIS
            Substitute user for PowerShell.
 
        .DESCRIPTION
            Open a terminal or execute a command as Administrator.
 
        .PARAMETER ScriptBlock
            Specifies the commands to run.
 
            Enclose the commands in curly braces { } to create a script block.
 
        .PARAMETER ArgumentList
            Supplies the values of local variables in the command.
 
            The variables in the command are replaced by these values before the command is run on the remote computer.
            Enter the values in a comma-separated list. Values are associated with variables in the order that they're listed.
    #>


    [Alias('su', 'sudo')]
    [CmdletBinding(DefaultParameterSetName = 'Terminal')]

    param (
        [Alias('command')]
        [Parameter(Mandatory = $true, ParameterSetName = 'Command', Position = 0)]
        [scriptblock]$ScriptBlock,

        [Alias('args')]
        [Parameter(ParameterSetName = 'Command', Position = 1)]
        [string[]]$ArgumentList
    )

    $process = [System.Diagnostics.Process]::GetCurrentProcess()

    $parameters = @{
        FilePath = $process.Path
        Verb = 'RunAs'
    }

    if ($PSBoundParameters.ContainsKey('ScriptBlock')) {
        $command = [System.Collections.Generic.List[string]]::new()
        $string = '"& {' + ($ScriptBlock -replace '"', '\"') + '}"'

        $command.Add('-Command')
        $command.Add($string)

        if ($PSBoundParameters.ContainsKey('ArgumentList')) {
            $ArgumentList | ForEach-Object {
                $argument = $PSItem

                $argument = $argument -replace '"', '\"'
                $argument = $argument -replace "'", "''"

                if ($argument -notmatch '^-') {
                    $argument = $argument -replace '^|$', "'"
                }

                $command.Add($argument)
            }
        }

        $parameters.Add('ArgumentList', $command)
    }

    Start-Process @parameters -Wait
# }