INTRODUCTION

I have previously written a blog post on how to elevate within an already opened Powershell window.
In this blog post I will provide a Powershell snippet which you can use in Powershell scripting to check if the Powershell script is running as administrator.

SOLUTION

DESCRIPTION

The below script snippet will look if the current user running the script is in the local administrator group.

THE SCRIPT SNIPPET

Add this to the top of your Powershell script:

Begin {
    #Checks if the user is in the administrator group. Warns and stops if the user is not.
    if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
        Write-Warning "You are not running this as local administrator. Run it again in an elevated prompt." ; break
    }

SUMMARY

Checking if the script is being run with administrator privileges can save you a lot of headaches.

I hope the above solution has been helpful to you. Don’t forget to leave a comment 🙂

RELATED POSTS