Code to check for Administrator privileges not working on some servers

1.3k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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
}
0
On

Older versions of PowerShell don't seem to like the backtick at IsInRole(`. This would normally be used to indicate the code statement continues onto the next line, but here it is used in the middle of a line.

Newer versions of PowerShell seem to tolerate backticks in the middle of the code, but it seems like older versions insist on it being the last character on the line.

If you put a linebreak directly after the ` as below (or if you just remove it), it should work in older PowerShells.

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
}

I've also changed your curly quotes to ASCII ones, just in case.