Administrative privileges

穿精又带淫゛_ 提交于 2019-12-12 22:40:45

问题


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
}


来源:https://stackoverflow.com/questions/18674801/administrative-privileges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!