Powershell 连接目录中的所有.csv文件,包括文件名并控制数据格式
我在powershell中有一些代码是从internet上获取的(我对powershell很陌生),用于连接我目录中的所有.csv文件,包括文件名。但是,输出文件格式不是我想要的。我想在我的输出文件中:Powershell 连接目录中的所有.csv文件,包括文件名并控制数据格式,powershell,concatenation,Powershell,Concatenation,我在powershell中有一些代码是从internet上获取的(我对powershell很陌生),用于连接我目录中的所有.csv文件,包括文件名。但是,输出文件格式不是我想要的。我想在我的输出文件中: filename data1 data2 data3 etc 相反,我得到的是: filename data1 data2 data3 etc 我的原始.csv文件采用以下格式: data1 data2 data3 如何修改代码以实现这一点 谢谢 dir $csvFilesPath\*.c
filename
data1
data2
data3
etc
相反,我得到的是:
filename
data1 data2 data3 etc
我的原始.csv文件采用以下格式:
data1
data2
data3
如何修改代码以实现这一点
谢谢
dir $csvFilesPath\*.csv | ForEach {
$variable = "$($_.Name)`n$(Get-content $_.FullName)"
Add-Content -Value $variable -Path $csvFilesPath\output.txt
}
在了解了一些其他人的建议后,我能够使用此代码实现一些我可以使用的东西:
'''
#这段代码遍历所有csv文件并添加文件名
添加到每个文件中名为filename的新列下的每一行
Get-ChildItem "$csvFilesPath\*.csv" | ForEach-Object {
$CSV = Import-CSV -Path $_.FullName -Delimiter ","
$FileName = $_.Name
$CSV | Select-Object *,@{N='Filename';E={$FileName}} | Export-CSV
$_.FullName -NTI -Delimiter ","
}
# this code gets all of the .csv files and concatenates all of them into
an output.csv file
import-csv (Get-ChildItem $csvFilesPath\*.csv) | export-csv
$csvFilesPath\output.csv -NoTypeInformation
'''
谢谢大家的帮助 我想这可能适合你。有几件事需要注意
CSV文件是平面水平文件。[grin]它们有数据行,其中每一列都位于行中的字段上。所以源CSV文件的布局是什么?您显示的不是完整的CSV文件,因为它缺少标题行和其他列。您的数据看起来像一个简单的文本文件…考虑使用<代码>导入CSV 和<代码>导出CSV 而不是<代码>获取内容< /代码>和<代码>添加内容< /代码>…Hi-Lee - CSV文件就像我上面写的那样。它有两列和几行,具体取决于文件长度。数据在单独的行中。看来我的连接脚本正在退出回车。@ccasey27这可能是因为您使用了
Get Content
。跟随什么@JosefZsaid@ccasey27-示例数据仅显示一列,其中包含3个数据行,没有标题行。。。第二栏在哪里?
# Make a list for storing the variables. There is no point to access them twice.
[System.Collections.Generic.List[object]]$contentsList = [System.Collections.Generic.List[object]]::new()
# Get-ChildItem and dir do the same thing
Get-ChildItem "$csvFilesPath\*.csv" | ForEach-Object {
# Importing the Csv
$CSV = Import-CSV -Path $_.FullName
# Add the FileName NoteProperty. This is what powershell turns your Csv headers into.
$CSV | Add-Member -NotePropertyName FileName -NotePropertyValue $_.Name
# Add every row of the current csv file to the contentsList variable
$contentsList.AddRange($CSV)
# Export the current csv back to it's original location.
# This is done to add the FileName column.
# If you don't want to add that column to the actual files, then just comment out the line below.
$CSV | Export-Csv -Path $_.FullName -NoTypeInformation
}
# Finally take the contentsList variable and export it to your csv output file
$contentsList | Export-Csv "$csvFilesPath\output.csv" -NoTypeInformation