从CSV文件导入数据时,在PowerShell中将字符串转换为布尔值

时间:2019-02-06 00:45:24

标签: powershell csv boolean migration exchange-server

我要将本地Exchange环境迁移到Office 365,目前正在尝试编写一些迁移任务的脚本。特别的一项任务是从本地环境中将组和组成员导出为CSV,然后将CSV数据导入Office 365。

我创建了以下脚本,尝试将组导入Office 365:

# Import distribution groups from CSV to Office 365
Import-Csv c:\admin\exchange-migration\exports\distribution-groups.csv | foreach {
    New-DistributionGroup -Name $_.name -Alias $_.alias -PrimarySmtpAddress $_.primarysmtpaddress -Type Distribution -RequireSenderAuthenticationEnabled ([System.Convert]::ToBoolean($_.requiresenderauthenticationenable))
}

我在使用“ requiresenderauthenticationenabled”部分时遇到了麻烦,因为我无法将字符串转换为布尔值,但是经过一番研究,我想到了[System.Convert]选项。但是,现在每个值都被视为FALSE。

Here's my CSV

1 个答案:

答案 0 :(得分:0)

Mathias R. Jessen提供了关键的指针:

您在传递给[System.Convert]::ToBoolean()的属性名称中有错字,这导致该属性引用始终评估为$null ,. NET方法始终将其转换为$falseSet-StrictMode -Version 2

要在以后防止此类错字,您可以设置Set-StrictMode -Version 2 # Try to reference a nonexistent property on an input object. [pscustomobject] @{ one = 1; two = 2; three = 3 } | % { $_.four } # -> Error "The property 'four' cannot be found on this object. # Verify that the property exists" 或更高的值,如果引用了未初始化的变量或不存在的属性,则将报告语句终止错误:< / p>

true

但是,不幸的是,这种严格模式可能会带来有害的副作用:


除了输入错误外,一种将false-eq 'true'(无论如何变化)的字符串值强制为对应的布尔值的简单方法是使用... -RequireSenderAuthenticationEnabled ($_.requiresenderauthenticationenabled -eq 'true');例如:
'true'

也就是说,这只有在您可以依赖于将属性值限制为字符串'false''yes'的情况下才是可靠的-您不会以这种方式捕获意外值,例如{{1 }}。


顺便说一句,不幸的是,New-DistributionGroup类型的参数使用[bool]类型的参数而不是[switch]类型的参数是与PowerShell约定的冲突。。

如果将-RequireSenderAuthenticationEnabled正确键入为[switch]

代替

-RequireSenderAuthenticationEnabled $true

您只需传递开关名称本身即可

-RequireSenderAuthenticationEnabled

,而不是

-RequireSenderAuthenticationEnabled $false

您想要的:

  • 通常只需省略开关
  • 但是如果您通过存储在变量中的布尔值以编程方式构建参数 ,则可以使用-RequireSenderAuthenticationEnabled:$var-注意开关名称之间必需的:和布尔值。