MGoBlue93
MGoBlue93

Reputation: 684

How to test a boolean in powershell?

I have a powershell script which looks to make sure someone is running the script as an admin.

The variable $currentPrincipal returns true or false.

Here is the code:

$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

If ($currentPrincipal -eq $true) {

    Write-host "yay"
}
Else {

   Write-Host "boo"

}

But when running as an admin AND currentPrincipal is true, it still falls through to the else... here is the CLI which shows that:

PS C:\WINDOWS\system32> C:\Users\dogzilla\Desktop\SetSQLServerToManual.ps1
True
boo

My question is, what is the proper way to evaluate a boolean in powershell?

Upvotes: 0

Views: 3915

Answers (2)

RoadRunner
RoadRunner

Reputation: 26315

Your currently just calling WindowsPrincipal.IsInRole, which will output the Boolean result. Additionally, $currentPrincipal is of type System.Security.Principal.WindowsPrincipal, which is not a Boolean. I would ammend your code to store the result of IsInRole() as a variable and checking that instead.

$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$checkRole = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

If ($checkRole -eq $true) {
    Write-host "yay"
}
Else {
    Write-Host "boo"
}

Upvotes: 3

js2010
js2010

Reputation: 27428

This is the way to test it:

if ( ($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) -eq $true )

Upvotes: 0

Related Questions