How to convert string to boolean in this Powershell code for Exchange Online?

自作多情 提交于 2019-12-11 02:07:10

问题


My code is:

Import-Csv "$env:userprofile\Desktop\ExternalContacts.csv"| foreach {New-MailContact -Name $_.Name -DisplayName $_.Name -ExternalEmailAddress $_.ExternalEmailAddress -FirstName $_.FirstName -LastName $_.LastName | Set-MailContact -Identity $_.Name -HiddenFromAddressListsEnabled $_.HiddenFromAddressListsEnabled}

And I am getting:

Cannot process argument transformation on parameter 'HiddenFromAddressListsEnabled'. Cannot convert value "System.String" to type "System.Boolean", parameters of this type only accept booleans or numbers, use $true, $false, 1 or 0 instead.

Here are the first two rows of my CSV file as viewed in Notepad:

Name,FirstName,LastName,ExternalEmailAddress,HiddenFromAddressListsEnabled
Ted Testington,Ted,Testington,ted.testington@blah.com,$true

How can I do the necessary conversion?

Thanks.


回答1:


Be careful with -as. It only works when a string is 0 or 1.

Both ("FALSE") -as [bool] and [bool]("FALSE") will return True!

It's better to use

[System.Convert]::ToBoolean("FALSE")
[System.Convert]::ToBoolean("False")
[System.Convert]::ToBoolean(0)

Or Parse

[bool]::Parse("FALSE")
[bool]::TryParse("FALSE", $outputVariable) # Will not raise an exception if the parse fails

Parse only works with strings as parameter.




回答2:


You can also use the -as operator

-HiddenFromAddressListsEnabled ($_.HiddenFromAddressListsEnabled -as [bool])


来源:https://stackoverflow.com/questions/16983810/how-to-convert-string-to-boolean-in-this-powershell-code-for-exchange-online

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!