Jon

PowerShell script to self-elevate

6 posts in this topic

#1 ·  Posted (edited)

I'm writing a set of PowerShell scripts/library for Windows 10 builds. One thing I often want to do is to browse to the location of a script that is part of a larger group of scripts and run it manually to do an install or make a one off change. So I like all my scripts to work well whether run from a task sequence or double-clicked in explorer.

Most of my build scripts rely on having admin rights so I like to make them able to self-elevate if required - or at least give an error message. In PowerShell 4.0 (Windows 8.1) they added the #Requires -RunAsAdministrator statement but this won't do it for you - it just causes the script to abort if not admin. 

Below is a PowerShell script that does the following:

  • Checks for admin rights using the Test-IsAdmin function
  • If not admin:
    • Get the full script path and working directory using the Get-UNCFromPath function
    • If the paths are mapped drives then get the UNC version (drive mappings are lost when elevating from user to admin in most configurations)
    • Execute PowerShell.exe with the UNC path of the script and the RunAs verb to trigger elevation. ExecutionPolicy is also set to Bypass on the command line. The working directory is also set to the UNC path version.
    • Waits for the new process to finish, and captures its return code
    • Exits using the same return code

Script is as follows:

# Test if admin
function Test-IsAdmin() 
{
    # Get the current ID and its security principal
    $windowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $windowsPrincipal = new-object System.Security.Principal.WindowsPrincipal($windowsID)
 
    # Get the Admin role security principal
    $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
 
    # Are we an admin role?
    if ($windowsPrincipal.IsInRole($adminRole))
    {
        $true
    }
    else
    {
        $false
    }
}


# Get UNC path from mapped drive
function Get-UNCFromPath
{
   Param(
    [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
    [String]
    $Path)

    if ($Path.Contains([io.path]::VolumeSeparatorChar)) 
    {
        $psdrive = Get-PSDrive -Name $Path.Substring(0, 1) -PSProvider 'FileSystem'

        # Is it a mapped drive?
        if ($psdrive.DisplayRoot) 
        {
            $Path = $Path.Replace($psdrive.Name + [io.path]::VolumeSeparatorChar, $psdrive.DisplayRoot)
        }
    }

    return $Path
 }


# Relaunch the script if not admin
function Invoke-RequireAdmin
{
    Param(
    [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
    [System.Management.Automation.InvocationInfo]
    $MyInvocation)

    if (-not (Test-IsAdmin))
    {
        # Get the script path
        $scriptPath = $MyInvocation.MyCommand.Path
        $scriptPath = Get-UNCFromPath -Path $scriptPath

        # Need to quote the paths in case of spaces
        $scriptPath = '"' + $scriptPath + '"'

        # Build base arguments for powershell.exe
        [string[]]$argList = @('-NoLogo -NoProfile', '-ExecutionPolicy Bypass', '-File', $scriptPath)

        # Add 
        $argList += $MyInvocation.BoundParameters.GetEnumerator() | Foreach {"-$($_.Key)", "$($_.Value)"}
        $argList += $MyInvocation.UnboundArguments

        try
        {    
            $process = Start-Process PowerShell.exe -PassThru -Verb Runas -Wait -WorkingDirectory $pwd -ArgumentList $argList
            exit $process.ExitCode
        }
        catch {}

        # Generic failure code
        exit 1 
    }
}


# Relaunch if not admin
Invoke-RequireAdmin $script:MyInvocation

# Running as admin if here
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("Script is running as admin", 0, "Done", 0x1) | Out-Null

 

Edited by Jon
3 people like this

Share this post


Link to post
Share on other sites



I feel I'm reading Chinese when I look at PowerShell scripts, am I the only one?

Share this post


Link to post
Share on other sites

Well :: is used for static methods/properties in PHP, though I have to admit it's like a mixture of everything in there.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

There appears to be a module in Windows 10 Powershell called AutoItX that includes Assert-AU3IsAdmin.  It returns 1 if run as administrator and 0 if not.  At least on my machine.  YMMV.


David Nuttall
Nuttall Computer Consulting

An Aquarius born during the Age of Aquarius

AutoIt allows me to re-invent the wheel so much faster.

I'm off to write a wizard, a wonderful wizard of odd...

Share this post


Link to post
Share on other sites

Hey, don't know if you are still looking for a solution, but if you past the following code at the beginning of your powershell script, it will elevate it for you

function Use-RunAs 
{    
    # Check if script is running as Adminstrator and if not use RunAs 
    # Use Check Switch to check if admin 
     
    param([Switch]$Check) 
     
    $IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()` 
        ).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator") 
         
    if ($Check) { return $IsAdmin }     
 
    if ($MyInvocation.ScriptName -ne "") 
    {  
        if (-not $IsAdmin)  
        {  
            try 
            {  
                $arg = "-file `"$($MyInvocation.ScriptName)`"" 
                Start-Process "$psHome\powershell.exe" -Verb Runas -ArgumentList $arg -ErrorAction 'stop'  
            } 
            catch 
            { 
                Write-Warning "Error - Failed to restart script with runas"  
                break               
            } 
            exit # Quit this session of powershell 
        }  
    }  
    else  
    {  
        Write-Warning "Error - Script must be saved as a .ps1 file first"  
        break  
    }  
} 
 
 
 
 
 
 
# Example 
Use-RunAs

(Rest of code goes here)

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • ur
      By ur
      I am maintaining all the reusable code in a separate file as library.au3.
      In that file I have referenced some dependent files using fileinstall, so that they will be extracted when necessary.
       
      Problem is, if I use a function in the library.au3 in another script which doesn't require this dependent file, as I am including the whole file using include tag, it is embedding that file also.
      Is there any way to exclude that.
       
    • tcurran
      By tcurran
      Here's a short UDF that will, at least in most cases, detect whether a window can be copied from or pasted to programmatically--for example, by Send()ing ctl-c, ctl-v. This is often disabled when programs (like your AutoIt script) run at a lower UAC integrity level than the application they are trying to operate on.
      #include <WinAPI.au3> Func _WindowIsPasteable($handle) ;accepts window handle; returns true or false whether a window will accept Ctl-C, Ctl-V Local $bCanPaste = True Local $hTestWindowPID = 0 Local $hTestWindowTID = _WinAPI_GetWindowThreadProcessId($handle, $hTestWindowPID) _WinAPI_AttachThreadInput(_WinAPI_GetCurrentThreadId(), $hTestWindowTID, True);attach to window we want to paste into $bCanPaste = _WinAPI_GetFocus() ;Test whether window is paste-able--returns False if it is not _WinAPI_AttachThreadInput(_WinAPI_GetCurrentThreadId, $hTestWindowTID, False);detach from window thread Return $bCanPaste EndFunc Pass it a window handle; it returns true or false whether a window will accept programmatic pasting. The function may not work on the CMD window, since it handles the clipboard uniquely.
      This function works by attaching to the program thread of the window whose handle it receives, then attempting to perform a GetFocus on that thread. In most cases, the attempt will fail if the window will not accept programmatic copy-paste.
    • david1337
      By david1337
      Hi guys,
      I need a little help here
      I have this simple Powershell script, that is able to set "sig.htm" as signature in OWA for the mail account specified.
      First part of the script just loads the Exchange snapin, since this is needed for the Get-Mailbox command.
      #Add Exchange 2010/2013 snapin if not already loaded in the PowerShell session if (!(Get-PSSnapin | where {$_.Name -eq "Microsoft.Exchange.Management.PowerShell.E2010"})) { try { Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction STOP } catch { #Snapin was not loaded Write-Warning $_.Exception.Message EXIT } . $env:ExchangeInstallPath\bin\RemoteExchange.ps1 Connect-ExchangeServer -auto -AllowClobber } $mailboxes = Get-Mailbox -Identity user@domain.com $mailboxes| foreach {$file= "sig.htm"; Set-MailboxMessageConfiguration -identity $_.alias -SignatureHtml "$(Get-Content -Path $file -ReadCount 0)"} What I want is for AutoIt to use Powershell.exe to run the script somehow. This way I would be able to use AutoIt variables and arrays together with the PS script.
       I guess the solution would be to run Powershell.exe with command line arguments?
      If that is not possible, maybe have the script stored as a "ps1" file, and interact with it that way? (not preferred)
    • tcox8
      By tcox8
      Hello,
      Currently I am running a script that calls a powershell script. To read the results of that I am reading StdOut. I am parsing things accordingly but unfortunately it doesn't parse correctly all the time and I end up missing parts of the string or other problems. My question then is, what is the best results for reading what is returned when running a powershell script or something similar?
    • WoodGrain
      By WoodGrain
      Hi guys,
      This is probably an obvious one, but I really don't use this command at all so am hoping you can spot my mistake.
      I'm running a powershell script on a schedule with the following script in a function, the function is being called in a loop, but the console process is not closing in the background and I end up with a bunch of console windows running in the background:
      Run(@comspec & ' /k PowerShell.exe -STA -NonInteractive -ExecutionPolicy ByPass -Command "& ''Z:\Powershell\365\GetNextDetails.ps1'' "', "", @SW_HIDE) Thanks!