Monday, April 1, 2013

Powershell - RunAsAdminAlways Function

Here is a function I use in many of my powershell scripts to check if they have been launched with elevated privileges. If it has then it just changes the window color and title. If it has not it is relaunched with those privileges.

If you create a PS1 file with all the code below and then replace everything below the "Stuff to be run in an elevated prompt goes below here." comment it will ensure that code is executed in an elevated command prompt.

Of course you could also always grab just the function and call it from one of your own existing script(s).

Function RunAsAdminAlways ($command) {
#* Function: RunAsAdminAlways
#* Created: [02/15/2011]
#* Author: Charles Ulrich
#* Arguments: Should always be called with 
#* $myInvocation.MyCommand.Definition as the only argument
#* Ex: $y = RunAsAdminAlways ($myInvocation.MyCommand.Definition)
#* Purpose: Checks if script is running as admin
#* and relaunches if not.

# Get the ID and security principal of the current user account
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
# Get the security principal for the Administrator role
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
    # We are running "as Administrator" - so change the title and background color to indicate this
    $Host.UI.RawUI.WindowTitle = $command + "(Elevated)"
    $Host.UI.RawUI.BackgroundColor = "DarkBlue"
    # We are not running "as Administrator" - so relaunch as administrator
    Start-Process powershell -ArgumentList $command -verb "runas"
    # Exit from the current, unelevated, process

$y = RunAsAdminAlways ($myInvocation.MyCommand.Definition)

# Stuff to be run in an elevated prompt goes below here.

Write-Host "Looks Good!"
Write-Host "Press any key to continue."

$z = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")