PoshCode Archive  Artifact [b39023d164]

Artifact b39023d1646c419f020a9c52c999f857e0741bfe43fb7dddcab68f1a14ba7779:

  • File sudo-for-Powershell.ps1 — part of check-in [394c12dc21] at 2018-06-10 13:02:20 on branch trunk — Updated from other people’s attempts. Useful for calling programs (notepad.exe, etc) or for running powershell scripts in an elevated prompt (use the -ps flag) (user: pezhore size: 2670)

# encoding: ascii
# api: powershell
# title: sudo for Powershell
# description: Updated from other people’s attempts. Useful for calling programs (notepad.exe, etc) or for running powershell scripts in an elevated prompt (use the -ps flag)
# version: 1.3
# type: script
# author: pezhore
# license: CC0
# x-poshcode-id: 1874
# x-derived-from-id: 3056
# x-archived: 2017-05-22T04:45:26
# x-published: 2011-05-25T09:54:00
#
#
# sudo.ps1
#
# Authors: pezhore, mrigns, This guy: http://tsukasa.jidder.de/blog/2008/03/15/scripting-sudo-with-powershell
#          Other powershell peoples.
#
# Sources:
#       http://tsukasa.jidder.de/blog/2008/03/15/scripting-sudo-with-powershell
#       http://www.ainotenshi.org/%E2%80%98sudo%E2%80%99-for-powershell-sorta
#
# Version:
#       1.0     Initial version
#       1.1     added -ps flag, cleaned up passed $file/$script full path
#       1.2     Comments
#       1.3     Fixed passing working directory to powershell/auto closing

param(
        [switch]$ps,               # Switch for running args as powershell script
        [string]$file,             # Script/Program to run
        [string]$arguments = $args # Arguments to program/script
     )

# Find our powershell full path
$powershell = (get-command powershell).definition

# Get current directory
$dir = get-location

#If we're running this as a elevated powershell script
if ($ps){

        # Script verification
        if([System.IO.File]::Exists("$(get-location)\$file")) {

                # Set the $script to full path of the ps script
                $script = (get-childitem $file).fullname
        }

        # Create a powershell process
        $psi = new-object System.Diagnostics.ProcessStartInfo $powershell

        $psi.WorkingDirectory = Get-Location

        # Combine the script and its arguments
        $sArgs = $script + " " + $arguments

        # Set the arguments to be the ps script and it's arguments
        $psi.Arguments = "-noexit -command set-location $dir; $sArgs"

        # Magic to run as elevated
        $psi.Verb = "runas";
}

# We're running something other than a powershells script
else {

        # File verification
        if([System.IO.File]::Exists("$(get-location)\$file")) {

                # Get full path
                $file = (get-childitem $file).fullname
        }

        # Same as above, create proccess/arguments/runas
        $psi = new-object System.Diagnostics.ProcessStartInfo $file
        $psi.Arguments = $arguments
        $psi.Verb = "runas"
}

# Start the process
[System.Diagnostics.Process]::Start($psi)