Switch on, switch off. Enabled, disabled. Up, Down. All possible wordings for $true and $false in PowerShell. Unfortunately, there is no simple way to toggle between 2 variables when not using these boolean values.

$variable = $True$variable = ! $variable

## Hurray for the array

Luckily, every item in an array comes with an index. Therefore we can easily find the index of an item. We can just use the .indexof() function.

$array = @("Item1", "Item2", "Item3")$array.indexof("Item3")2

We also have a great property in the world of natural numbers. When dividing by 2 we always return a remainder of 0 or 1. PowerShell likes 0’s and 1’s. The modulo operator will gladly help calculate this remainder.

2%203%21

## Exploiting the remainder

We can use this index to determine it’s boolean state. An even index gives a remainder of 0. Uneven indexes result in a 1. This we can use as $False (0) or $True (1).

$BooleanArray = @( "Off", "On", "Disabled", "Enabled", "Down", "Up", 0, 1, $False, $True)$BooleanArray.indexof("Down")%20$BooleanArray.indexof("Up")%21

Now, an easy toggle function which you can adapt for your needs.

function Toggle-Boolean {Param([Parameter(Position=1)]$Boolean)$BooleanArray = @( "Off", "On", "Disabled", "Enabled", "Down", "Up", 0, 1, $False, $True)$BooleanIndex = $BooleanArray.indexof($Boolean)if ($BooleanIndex % 2) {$SwitchedBoolean = $BooleanArray[($BooleanIndex - 1)]}elseif (!($BooleanIndex % 2)) {$SwitchedBoolean = $BooleanArray[($BooleanIndex + 1)]}$SwitchedBoolean}

Now all we need is a use for this function. If you have suggestions, leave a comment below ðŸ˜‰