Administrative privileges

2019-08-07 17:08发布

问题:

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.

回答1:

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.



回答2:

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
}