Wednesday, April 22, 2015

Check if your script are running in administrator context

Doing system changes via a script files will often require that you run it in the context of administrator.

Doing this with script I run myself is easy enough, I know that if it fails it is because I forgot to use "Run as administrator" when I started it (or did a poor job creating the script).
However when creating scripts that other people will run it will be a good idea to add a check in the script and give feedback to the person running it.
Doing this from Powershell:
You need to create a function to do this from Powershell, or integrate it in the script.

function Test-IsAdmin {
([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")

More info HERE

 Doing this from a command line file (cmd):

 You can use "net session >nul 2>&1" to check and add one scenarios if success and another if failed. In my example, I just use the goto command since this gives a better structur to the script.

Example script that adds a line to the hosts. file (needs to be admin for this):

@echo off
goto check_Permissions

 echo Administrative permissions required. Detecting permissions...
    net session >nul 2>&1
    if %errorLevel% == 0 goto Success else goto Error
 echo Failure: Current permissions inadequate.
 echo "! You need to run this as administrator"
 echo "! Right click the file and select Run As Administrator"
goto END

 echo >>  %Windir%\system32\drivers\etc\hosts.
 echo "! Changes successfull"

Feedback when unsuccessfull:

Feedback when unsuccessfull:
And the end result of this script:-)
Just put in the commands or whatever you want in the :Success section of the script to be executed if it's running as administrator. And the message or commands you want to be executed if it's not running as administrator in the :Error section.

Test-MigrationReadyness.ps1 Script

I have added a OneDrive/SharePoint migration related script to my GitHub This is an add-on to make my script " Test-OneDrivePath.ps1...