【问题标题】:Converting string to boolean in PowerShell when importing data from a CSV file从 CSV 文件导入数据时在 PowerShell 中将字符串转换为布尔值
【发布时间】:2019-06-29 21:48:33
【问题描述】:

我正在将本地 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。

【问题讨论】:

  • 您的示例代码中requiresenderauthenticationenable 末尾缺少一个“d”
  • 啊。这样就可以了。现在一切都好。

标签: powershell csv boolean migration exchange-server


【解决方案1】:

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

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

为了以后防止此类拼写错误,您可以设置Set-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"

不幸的是,这种严格模式有潜在的副作用:


除了拼写错误之外,一种将truefalse(在任何情况下的变化)的字符串值强制为相应的布尔值的更简单方法是使用-eq 'true' ;例如:
... -RequireSenderAuthenticationEnabled ($_.requiresenderauthenticationenabled -eq 'true')

也就是说,只有当您可以将属性值限制为字符串 'true''false' 时,这才是可靠的 - 您不会以这种方式捕获意外值,例如 'yes'


顺便说一句,New-DistributionGroup 使用[bool]-typed 参数而不是使用[switch]-typed 参数是对PowerShell 惯例的不幸偏离

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

代替

-RequireSenderAuthenticationEnabled $true

您只需传递开关名称本身:

-RequireSenderAuthenticationEnabled

而不是

-RequireSenderAuthenticationEnabled $false

你会:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    相关资源
    最近更新 更多