如何使用 PowerShell 检查 csv 列中的空行

问题描述 投票:0回答:1

我在名为“Exchange Mailboxes”的 csv 列中混合了数据(有些行是空的)。

Exchange Mailboxes
Include:[[email protected]] 
Include:[[email protected]]

Include:[[email protected]]

我尝试先检查该行是否为空。如果它是空的,那么只为这些行分配空字符串。如果特定的 csv 行不为空,则使用 EXOMailbox 获取其名称和 ID。

换句话说,如何跳过空行?

我尝试了这样的方法,但由于某些原因它不起作用。

$importFile = Import-Csv -Path "C:\AuditLogSearch\Dis\Modified-Audit-Log-Records.csv"

 foreach ($csvFile in $importFile){
    if([string]::IsNullOrEmpty($csvFile.'Exchange Mailboxes')){

      $userName = ""
      $userId = ""

    }else{
      $exoMailbox = $csvFile.'Exchange Mailboxes'.Split([char[]]@('[', ']'))[1]
      $exoUser = Get-EXOMailbox -Filter "PrimarySmtpAddress -eq  '$exoMailbox'"

      $userName = $exoUser.DisplayName
      $userId = $exoUser.Identity

    }

}
powershell csv powershell-4.0
1个回答
3
投票

如果要排除具有空

Exchange Mailboxes
列值的行:

$importFile = 
  Import-Csv "C:\AuditLogSearch\Dis\Modified-Audit-Log-Records.csv" |
  Where-Object 'Exchange Mailboxes' -ne ''

如果您想排除 all 列为空的行(这也适用于您的(非典型)列 CSV):

$importFile = 
  Import-Csv "C:\AuditLogSearch\Dis\Modified-Audit-Log-Records.csv" |
  Where-Object { -join $_.psobject.Properties.Value }

注:

  • Import-Csv
    将 CSV 文件的行解析为
    [pscustomobject]
    实例,其属性始终反映 CSV 的列值作为字符串

  • $_.psobject.Properties.Value
    使用 内在
    .psobject
    属性
    来反映对象的所有属性,并且
    .Properties.Value
    返回所有属性值。

    • -join
      运算符的一元形式直接连接所有(根据定义string)值并将结果作为单个字符串返回。

    • 因此,如果 all 列值为空,则结果是 空字符串 (

      ''
      );否则,字符串非空

  • Where-Object
    ,当给定 脚本块 (
    { ... }
    ) 时,隐式将其输出强制为
    [bool]
    $true
    $false
    );在 PowerShell 中,将任何 非空 字符串转换为
    [bool]
    会产生
    $true
    ,而 空字符串 会产生
    $false


结合应用上述内容并从

Exchange Mailboxes
列值中提取电子邮件地址:

$emailAddresses = 
  Import-Csv "C:\AuditLogSearch\Dis\Modified-Audit-Log-Records.csv" |
  Where-Object { -join $_.psobject.Properties.Value } |
  ForEach-Object { ($_.'Exchange Mailboxes' -split '[][]')[1] }

根据您的示例输入,输出

$emailAddresses
然后产生:

[email protected]
[email protected]
[email protected]

适用于我认为的原始代码的意图:

$customObjects = 
  Import-Csv "C:\AuditLogSearch\Dis\Modified-Audit-Log-Records.csv" |
  Where-Object { -join $_.psobject.Properties.Value } |
  ForEach-Object { 
    $exoMailbox = ($_.'Exchange Mailboxes' -split '[][]')[1]
    $exoUser = Get-EXOMailbox -Filter "PrimarySmtpAddress -eq  '$exoMailbox'"
    # Construct and output a custom object with the properties of interest.
    [pscustomobject] @{  
      UserName = $exoUser.DisplayName
      UserId = $exoUser.Identity
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.