【问题标题】:How to remove CSV headers and keep columns seperate using Powershell如何使用 Powershell 删除 CSV 标题并保持列分开
【发布时间】:2019-12-31 10:03:55
【问题描述】:

我正在尝试根据第一列中的值将 CSV 拆分为 2。新创建的 CSV 不能有列名,这就是问题所在。当我删除标题时,所有值都进入第一列。

为了根据第一列值拆分 CSV,我必须分配标题。使用正确的值成功创建了 2 个新文件,但是我的最后一步是删除标题,因为用于处理 CSV 的应用程序将不接受列名。

删除标题后,所有值都不再用逗号分隔,因此都在第一列中。我该如何解决这个问题?

if (!(Test-Path X:)) {
    $net = New-Object -comobject Wscript.Network
    $net.MapNetworkDrive("X:","**Path**")
}

$file = Get-ChildItem -Path "**Path**"  | Where-Object {
    $_.LastWriteTime -gt (Get-Date).AddHours(-10) -and
    $_.Name -like '*.CSV*'
}

if ($file) {
    $filename = $file.FullName
    $date = (Get-Date).ToString("yyyyMMdd")
    $ExportPathJUO = "**Path**$date"
    $ExportPathWDA = "**Path**$date"

    ##Create Seperate Files in Staging Folder
    $csv = Import-Csv $filename -Header A,B,C,D,E,F,G
    $IDS = $csv | select -ExpandProperty A -Unique
    foreach ($ID in $IDS) {
        $csv | where {
            $_.A -like '*0000009*'
        } | Export-Csv $ExportPathJUO -NoTypeInformation
    }
    foreach ($ID in $IDS) {
        $csv | where {
            $_.A -like '*0000007*'
        } | Export-Csv $ExportPathWDA -NoTypeInformation
    }

    ##Remove Headers
    (Get-content $ExportPathJUO) |
        select -Skip 1 |
        Out-File -FilePath $ExportPathJUO -Force
    (Get-content $ExportPathWDA) |
        select -Skip 1 |
        Out-File -FilePath $ExportPathWDA -Force 
}

【问题讨论】:

  • 您将 Get-ChildItem $file 的结果视为单个项目,而不是使用 foreach 更好地迭代的可能数组。

标签: powershell csv header export


【解决方案1】:

如果您的 CSV 中没有/不想要标头,请不要使用 *-Csv cmdlet。你想要的可以这样完成:

foreach (line in Get-Content $filename) {
    $a = $line.Split(',')[0]
    switch -wildcard ($a) {
        '*0000007*' { $line | Add-Content $ExportPathWDA }
        '*0000009*' { $line | Add-Content $ExportPathJUO }
    }
}

【讨论】:

  • 虽然这在这种情况下可行,但在其中一个输入值中有转义逗号的情况下将不起作用。
  • @MartinBrown 是的。但我通常会尽量避免过度设计解决方案。
  • @AnsgarWiechers 只是想我会提到它,因为在我的职业生涯中,我花了太多时间在多个系统中修复该错误。只要人们意识到这个问题就可以了。
猜你喜欢
  • 1970-01-01
  • 2013-12-29
  • 2016-01-15
  • 2019-03-18
  • 2023-03-07
  • 1970-01-01
  • 2021-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多