PowerShell Quick Tip: Converting a String to a Boolean Value
Some PowerShell cmdlets include switch parameters, i.e. no arguments are typically supplied to them - they are either True / On when they are present and False / Off when they are not. However, it is also possible to explicitly specify them with $true and $false, e.g.
Typically you would not use this when working manually at the console, but what if you needed to automate a task using a switch parameter and set it to be On or Off based on values from a CSV or XML file, i.e. you supply the true or false as a string?
This can lead to some initially confusing behaviour; look at this example.
$persistent = “False” \[boolean\]$persistent
PowerShell appears to have converted our ‘false’ string to a Boolean ‘true’, not what we were expecting! This is because PowerShell will convert any string greater than 0 characters to a Boolean ‘true’, behaviour which is consistent across other programming languages.
So there are a couple of ways round this, either change your data to an empty string (which may not be possible of course)….
$persistent = “” \[boolean\]$persistent
or use the .Net System.Convert ToBoolean method:
$persistent = “False” \[System.Convert\]::ToBoolean($persistent)
Looking at a practical example of how you might use this take a look at working with one of the Citrix XenDesktop providers to create a Hypervisor Connection (more on this topic to come)
New-Item -Path xdhyp:\\Connections –Name $Name –HypervisorAddress $HypervisorAddress –UserName $UserName –Password $Password –ConnectionType $ConnectionType –Persist: (\[System.Convert\]::ToBoolean($persistent))
A more detailed explanation of this topic is well written up by Kirk Munro