我有一个文件夹,其子文件夹中充满了 csv 文件。 对于每个文件,我只想获取第三列并将其保存在另一个文件中。
示例:
文件数据1.csv
aa,bb,cc
cat,horse,"dog, bird"
4th,33,first and second
文件数据1列3.csv
cc
dog, bird
first and second
我尝试过但结果是错误的:
param ( [String] $Filename = '*.csv',
[String] $SourceDir = 'C:\Data\',
)
ForEach ($csvFile in Get-ChildItem -Path $SourceDir -Filter $Filename){
(Import-Csv $csvFile)
cut -d, -f 3 *.csv > *column3.csv
psobject
属性从Import-Csv
解析CSV数据的对象中确定每个文件的列名称,并提取第三个名称。
然后使用成员访问枚举从行(对象)中提取所有属性值。
Join-Path
与 -f
(格式运算符)结合使用,根据输入文件名确定合适的输出文件路径和名称。
# Import all rows.
$rows = Import-Csv $csvFile
# Determine the name of the third column
$thirdColName = ($rows[0].psobject.Properties.Name)[2]
# Determine a suitable output file path and name.
$outFile =
Join-Path $csvFile.DirectoryName ('{0}_column3.csv' -f $csvFile.BaseName)
# Output the header column
$thirdColName > $outFile
# Append the values of the third column
$rows.$thirdColName >> $outFile
注:
在 Windows PowerShell 中,
>
和 >>
创建“Unicode”(UTF-16LE) 文件,而在 PowerShell (Core) 7+ 中,它们创建无 BOM 的 UTF-8 文件。
Set-Content
和 Add-Content
以及 -Encoding
参数,但请注意,在 Windows PowerShell 中,您无法以这种方式创建 BOM-less UTF-8 文件(请参阅此答案用于解决方法)。