How to find out if a PowerShell script is executed as Administrator

Here is a PowerShell code snippet to find out if a script is run as Administrator:

 

if ($host.UI.RawUI.WindowTitle -inotmatch "Administrator") {

Write-Host "Please run this as administrator"
Read-Host “Close this window”

}

Advertisements
This entry was posted in Scripts and tagged , , . Bookmark the permalink.

One Response to How to find out if a PowerShell script is executed as Administrator

  1. dannybuoy says:

    Check out the ‘Elevation Powertoys for Vista’ script samples to auto elevate your script!

    http://blogs.technet.com/b/elevationpowertoys

    $myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
    $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
    $adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
    if ($myWindowsPrincipal.IsInRole($adminRole) -eq $false)
    {
    $newProcess = new-object System.Diagnostics.ProcessStartInfo “PowerShell”;
    $newProcess.Arguments = $myInvocation.MyCommand.Definition;
    $newProcess.Verb = “runas”;
    [System.Diagnostics.Process]::Start($newProcess);
    exit
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s