Wednesday, November 20, 2019

How to Check for Administrator Privileges in a PowerShell Script?

If you need to run PowerShell script with administrator privileges, you can directly check the current process for administrative privileges directly in the PS code.

The following PowerShell code can be used to check if the current script is running in “Run as Administrator” mode or not:

function Check-PSAdminPermission (){
   if (-NOT ([Security.Principal.WindowsPrincipal]`
      [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
      [Security.Principal.WindowsBuiltInRole] "Administrator")) {
         Return $false
   }
   else {
         Return $true
   }
}
 
Write-Host "Checking for administrative privileges …"
if (Check-PSAdminPermission) {
    Write-Host "Administrator permission detected" -ForegroundColor Green
}
else {
   Write-Host "Not enough rights to run this script `nOpen the PowerShell console with administrator privileges and run the script again" -ForegroundColor Yellow
    Break
}
 
Write-Host "Continue the script..."


Normal mode


Elevated mode/"Run as Administrator"


 

No comments:

Post a Comment