Boolean variable - does it need explicit conversion?

I’ve got a variable that needs to be a bool

Name: myBoolVar
Value: true
Scope: Production

Now in my deployment script I have

$myBoolVar = $OctopusParameters['myBoolVar']
if($myBoolVar) {
    # it's true
} else {
    # it's false
}

Is this good enough to work as is, or do I need to do an explicit conversion?

IE: If someone enters false into the variable, will it be $false or ! $null?

Hi Chase,

Thanks for reaching out. Octopus will always assign variables values as string. If someone enters false into the variable, it’ll be the same as doing $variable = "false". In your case you’re gonna have to validate like this

#validating against a string
if($myboolvar -eq "true"){
    # it's true
} else {
    # it's false
}

or if you really need to deal with a variable of type bool

#validating against a string to then assign a real bool value
if($Myboolvar -eq "true"){
$myboolvar = $true
}
else{
$Myboolvar = $false
}
if($myBoolVar) {
    # it's true
} else {
    # it's false
}

Thanks,

Dalmiro

Thanks for that,
can I not also just do

$myBoolVar = [System.Convert]::ToBoolean($OctopusParameters['MyBoolVar'])

In doing this, I will get a cast exception thrown if a user enters an invalid string.

Not only you can do that, but you also taught me something I didn’t knew!

win/win

Here’s how I’m setting up my overrides.

param( [hashtable] $poshBAR )

if ( $OctopusParameters ) { 
    $poshBAR.DisableWindowsFeaturesAdministration = [System.Convert]::ToBoolean($OctopusParameters['poshBAR.DisableWindowsFeaturesAdministration'])
    $poshBAR.DisableChocolateyInstallationAdministration = [System.Convert]::ToBoolean($OctopusParameters['poshBAR.DisableChocolateyInstallationAdministration'])
    $poshBAR.DisableHostFileAdministration = [System.Convert]::ToBoolean($OctopusParameters['poshBAR.DisableHostFileAdministration'])
}

return $poshBAR

I was just hoping that I didn’t have to do the cast, but it’s ok… this works.