Issue Description

  • I had to set HiddenFromAddressListsEnabled property of all mailboxes to $true or $false based on the input from a csv file.
  • I ran the script but I didn’t set the expected result.
  • Regardless of putting false or true in csv, everything was getting converted to True value.

Note : If you have experienced the similar issue, you can go straight to Fix Section.

input.csv Sample content

Powershell code – doesn’t work

$logMBerror = @()
#input csv file.
$csv = Import-Csv $home\desktop\input.csv
foreach($eachline in $csv){
        $HiddenFromAddressListsEnabled = $eachline.HiddenFromAddressListsEnabled
        $Mailbox = $eachline.Mailbox
Write-host $mailbox has HiddenFromAddressListsEnabled value set to $HiddenFromAddressListsEnabled -ForegroundColor Green
}

Reason

I looked into the reasons and found that regardless It has to do with these :

  • Above code converted the values in string and that was the reason it didn’t work.
  • Then i added [Boolean] in variable but it converted all false to True, It happened because powershell converts any string greater than 0 to a Boolean ‘true’.
$HiddenFromAddressListsEnabled = [Boolean]$eachline.HiddenFromAddressListsEnabled

Fix

You can use “[System.Convert]::ToBoolean()” or “[bool]::Parse()” to convert the value from string to boolean.

My testing confirmed that "[System.Convert]::ToBoolean()" works better than bool, So use this to convert the value and then use that in your code.
$HiddenFromAddressListsEnabled = [System.Convert]::ToBoolean($eachline.HiddenFromAddressListsEnabled)

Now, If you see TypeName is system.boolean and now my script works. You can use the similar to set any value, which accepts boolean value.

Powershell code – Rocks !

$csv = Import-Csv $home\desktop\input.csv
foreach($eachline in $csv){
        $HiddenFromAddressListsEnabled = [System.Convert]::ToBoolean($eachline.HiddenFromAddressListsEnabled)
        $Mailbox = $eachline.Mailbox
Write-host $mailbox has HiddenFromAddressListsEnabled value set to $HiddenFromAddressListsEnabled -ForegroundColor Green
}

Thank you for reading !

Advertisements

Advertisement