Administrators Jon Posted August 9, 2015 Administrators Share Posted August 9, 2015 (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 functionIf not admin:Get the full script path and working directory using the Get-UNCFromPath functionIf 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 codeExits using the same return codeScript is as follows:expandcollapse popup# 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 August 10, 2015 by Jon donoho, Danyfirex and jvanegmond 3 Deployment Blog: https://www.autoitconsulting.com/site/blog/ SCCM SDK Programming: https://www.autoitconsulting.com/site/sccm-sdk/ Link to comment Share on other sites More sharing options...
FaridAgl Posted August 9, 2015 Share Posted August 9, 2015 I feel I'm reading Chinese when I look at PowerShell scripts, am I the only one? http://faridaghili.ir Link to comment Share on other sites More sharing options...
guinness Posted August 9, 2015 Share Posted August 9, 2015 Well :: is used for static methods/properties in PHP, though I have to admit it's like a mixture of everything in there. UDF List: _AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018 Link to comment Share on other sites More sharing options...
Nutster Posted August 11, 2015 Share Posted August 11, 2015 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 NuttallNuttall 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... Link to comment Share on other sites More sharing options...
Administrators Jon Posted August 11, 2015 Author Administrators Share Posted August 11, 2015 Yeah, that's ours from the AutoIt installer Deployment Blog: https://www.autoitconsulting.com/site/blog/ SCCM SDK Programming: https://www.autoitconsulting.com/site/sccm-sdk/ Link to comment Share on other sites More sharing options...
MattHiggs Posted June 26, 2016 Share Posted June 26, 2016 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 expandcollapse popupfunction 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) Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now