1

In a thread here I found a way to check whether a user has administrative privileges. However, when I try to use boolean logic on this it fails to work.

$user = [Security.Principal.WindowsIdentity]::GetCurrent();
(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)  

if($user = $false){cls;Write-warning "Starting and stopping services can only be done with administrative privileges.`nPlease restart this script from an elevated prompt!";Read-host;exit
}

The problem is, whilst running the script from my computer without initiating Powershell with Administrative rights the text "False" comes up. However, the if statement does not kick in. Am I defining it wrong?

EDIT: When I use $true instead of $false the if statement kicks in both when I do and don't run the script from an elevated prompt.

Koterpillar
  • 7,883
  • 2
  • 25
  • 41

2 Answers2

6

There are 2 issues with your condition $user = $false:

  1. It's not a condition in the first place. = is an assignment operator, not a comparison operator. You need -eq to check for equality.
  2. $user is not a boolean value. What you actually want to check here is the return value of the IsInRole() method. However, you never assign it to a variable, so you can't use it elsewhere in your code.

Change your code to this:

$user    = [Security.Principal.WindowsIdentity]::GetCurrent()
$isAdmin = (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)

if (-not $isAdmin) {
  cls
  Write-warning "Starting and stopping services can ..."
  Read-host
  exit
}

and the problem will disappear.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • That makes perfect sense. I actually had the -eq in my original script. God knows why I wrote '=' here. I wonder however; where does the new object go when I don't assign it to a variable? Null? –  Sep 07 '13 at 16:42
  • It will linger in memory until the garbage collector disposes of it. – Ansgar Wiechers Sep 07 '13 at 18:34
0

It seems curious to me.. Can't you just update the following to be do the same checking:

if !($isAdmin) {
  cls
  Write-warning "Starting and stopping services can ..."
  Read-host
  exit
}
eckes
  • 64,417
  • 29
  • 168
  • 201
Leptonator
  • 3,379
  • 2
  • 38
  • 51
  • That would raise an error. `!` and `-not` have the same meaning (negate the next condition), but they **must** be inside the parentheses. – Ansgar Wiechers Sep 09 '13 at 14:00