按 header 名称从 CSV 导入指定列,并导出到新文件

Import specified columns from CSV, by header name, and export to new file

我想制作一个 ps1 将所有 .csv 放入一个文件夹,提取 2 列下的所有值(由 header 标识),然后为每个文件生成新的 .csv只有这两列。

我可以让它对单个文件起作用,如下所示,但是当我添加通配符时,它说该函数不适用于多个文件。我尝试过其他方法,但我没有正式的 CS 背景(所以我下面的 "script" 可能看起来很简陋);我接近了,但到目前为止没有任何效果。

$inputpath = 'C:/Users/AAA/AAA/AAA/AAA/'
$inputfile = 'BBB.csv'
$outputpath = $inputpath
$outputfile = $inputfile.basename + 'edited' + '.csv'

Import-Csv $inputpath$inputfile |
    select COLUMNtitle1, COLUMNtitle2 |
    Export-Csv -Path $outputpath$outputfile -NoTypeInformation

echo

由于您没有为 $inputfile 使用 Get-ChildItem,因此没有 basename 属性。此外,在连接路径时使用 Join-Path 更安全,最好避免使用 + 连接字符串。

$inputfolder = 'C:\Users\AAA\AAA\AAA\AAA\'
Get-ChildItem $inputfolder -include *.csv | % {
    $outputpath = Join-Path $inputfolder "$($_.basename)edited.csv"
    Import-Csv $_.fullname | select COLUMNtitle1,COLUMNtitle2 | Export-Csv -Path $outputpath -NoTypeInformation
}