2

I have the following variable:

$UPNSuffixChange = $True

In my script there's an if statement that will only run if this is true:

If ($UPNSuffixChange) {}

The idea being that the variable can be set to $False resulting in this section being skipped.

How can I restrict the value of this variable to only $True or $False to avoid mistyped values?

2
  • 1
    Who or what will assign the variable, though? Consider making $UPNSuffixChange a [switch] parameter of a function or the script as a whole, so passing the correct value is simple and natural. Cmdlets are much friendlier than loose scripts. Commented Aug 11, 2017 at 15:53
  • Thanks for the advice but there are multiple variables like this at the top of the script. I want it to fail right at the beginning should one of the variables not be set to either true or false rather than waiting until they get to the script section each one's responsible for and failing at that point instead. These variable are simply turning different sections on and off as required. Commented Aug 14, 2017 at 8:27

2 Answers 2

2

Strongly-type it is as a boolean:

[bool]$UPNSuffixChange = $True

If an attempt is made assign anything other than $true/$false (or the equivalents 1/0) to this variable, PowerShell will through the following error:

Cannot convert value "System.String" to type "System.Boolean". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0.

I used a System.String as an example; it is the same for other types.

Sign up to request clarification or add additional context in comments.

3 Comments

When it says "numbers" it really does mean "numbers": $UPNSuffixChange = 33.4 is legal (and assigns $True). [switch] $UPNSuffixChange = $true is more restrictive and will really only allow $False and $True. (Although whether you should use switch parameters like that is debatable.)
@JeroenMostert - Good point, I forget that 0 = $false, non-0 = $true is also a thing in PowerShell. I think the [switch] type matches OP's stated specs perfectly - consider posting as answer so I can upvote.
Thanks for the speedy response. [bool] works fine for this instance as will be a variable that other users of the script will set. I want this to error should they enter anything other than $true or $false for this variable.
2

You could use the SWITCH type. Switch can only be $true or $false. It is default $false.

[switch]$var = $true

if($var){
    "Var is TRUE"
}
If(!$var){
    "Var is FALSE"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.