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.
There are 2 issues with your condition
$user = $false
:=
is an assignment operator, not a comparison operator. You need-eq
to check for equality.$user
is not a boolean value. What you actually want to check here is the return value of theIsInRole()
method. However, you never assign it to a variable, so you can't use it elsewhere in your code.Change your code to this:
and the problem will disappear.
It seems curious to me.. Can't you just update the following to be do the same checking: