gpt4 book ai didi

performance - 使用Select-Object并使用Export-CSV进一步写入.csv文件时,是否可以不指定列名?

转载 作者:行者123 更新时间:2023-12-02 23:06:26 24 4
gpt4 key购买 nike

问题:1)字符串中的“$ FileName”,2)记录7000多个文件用了一个多小时。如何使录音更快?

Get-ChildItem "C:\*.csv" | ForEach-Object {
$CSV = Import-CSV -Path $_.FullName
$FileName = $_.Name

$CSV | Select-Object *,@{N='Filename';E={$FileName}} | Export-CSV $_.FullName
}

最佳答案

仅使用PowerShell代码即可加快此过程的唯一方法是诉诸纯文本处理:

Get-ChildItem C:\*.csv | ForEach-Object {  
$fileName = $_.Name
$toAppend = ',"Filename"'
$isHeaderRow = $true
$lines = switch -File $_.FullName {
default {
$_ + $toAppend # append to the line and output
if ($isHeaderRow) {
$isHeaderRow = $false
$toAppend = ',"{0}"' -f $fileName
}
}
}
# Write the updated lines back to the file.
# Adjust the -Encoding argument as needed.
Set-Content $_.FullName -Value $lines -Encoding utf8 -WhatIf
}
注意:上面命令中的 -WhatIf common parameter预览操作。确定操作将执行所需操作后,删除 -WhatIf
注意:
  • 带有switch参数的 -File 语句是一种逐行处理文本文件的有效方法。
  • 请注意,已更新的行$lines数组通过Set-Content参数传递到 -Value ,这比使用管道快得多($lines | Set-Content ...)
  • 该代码假定单个CSV文件可以整体容纳到内存中。如果那是不可能的,那么您将不得不切换到基于管道的解决方案,这会使速度变慢:& { switch ... } | Set-Content ...

  • 变体,其中所有 输入文件具有相同的列结构,并且将 合并到单个输出文件中:
    $outFile = './out.csv' # single output file
    $null = New-Item $outFile # initialize it (create it empty)

    $firstFile = $true
    Get-ChildItem C:\*.csv | ForEach-Object {
    $fileName = $_.Name
    $isHeaderRow = $true
    $lines = switch -File $_.FullName {
    default {
    if ($isHeaderRow) {
    $isHeaderRow = $false
    if ($firstFile) {
    $firstFile = $false
    $_ + ',"Filename"' # output single header row
    }
    # Construct string to append to this file's data rows.
    $toAppend = ',"{0}"' -f $fileName
    } else { # data row
    $_ + $toAppend # append to the line and output
    }
    }
    }
    # Append this file's updated lines to the output file.
    # Adjust the -Encoding argument as needed.
    Add-Content $outFile -Value $lines -Encoding utf8 -WhatIf
    }

    关于performance - 使用Select-Object并使用Export-CSV进一步写入.csv文件时,是否可以不指定列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64542002/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com