问题
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