powershelladministratoradministrative

Code to check for Administrator privileges not working on some servers


I have a line of code in a small script I wrote that checks if Powershell has administrative privileges before executing. The snippet with the administrative check below:

If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(` [Security.Principal.WindowsBuiltInRole] “Administrator”))
{
 Write-Warning “You do not have Administrator rights to run this script.`nPlease re-run this script as an Administrator.”
 Break
}

When certain customers run the script they receive the following error and I'm not sure why. Can someone please explain this to me?

Error message in PowerShell screenshot link

EDIT: To be clear, the script works fine on most servers or computers with PowerShell installed, it's only once in a while a customer will have an issue with the script.


Solution

  • It seems there are some strange quotes in your code, just after IsInRole(, use this code that works everytime :

    if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
        Write-Warning "You do not have Administrator rights to run this script.`nPlease re-run this script as an Administrator."
        Break
    }