简体   繁体   English

多个 csv 文件到一个 csv 文件 - Powershell

[英]Multiple csv files to one csv file - Powershell

I have been reading through some of the previous posts about the concept, but all the solutions i find very different from eachother.我一直在阅读有关该概念的一些以前的帖子,但是我发现所有解决方案彼此都非常不同。

I have multiple csv's devided over seperate folders (all with kind of the same path but the subfolders are different).我将多个 csv 划分到单独的文件夹(所有路径都相同,但子文件夹不同)。

I now need to import these csv's, change the headers and export it into one single csv.我现在需要导入这些 csv,更改标题并将其导出为一个 csv。

I have been trying with this but im getting a very weird error: Import-Csv : Cannot open file "C:\\Windows\\system32\\Book1.csv" Although my path is refering to C:\\csv ?我一直在尝试这个,但我得到了一个非常奇怪的错误:Import-Csv:Cannot open file "C:\\Windows\\system32\\Book1.csv" 虽然我的路径是指 C:\\csv ?

$CSVFolder = 'C:\csv\';                                                               #'
$OutputFile = 'C:\export\test3.csv';

$CSV= @();

Get-ChildItem -Path $CSVFolder -Filter *.csv | ForEach-Object { 
    $CSV += @(Import-Csv -Path $_)
}

$CSV | Export-Csv -Path $OutputFile -NoTypeInformation -Force;

I was thinking of using a datatable for the headers, but its not so clear to me at this point.我正在考虑为标题使用数据表,但此时我还不太清楚。 Also the issue with the error is not clear for me...错误的问题对我来说也不清楚......

As has been noted:正如已经指出的:

  • Import-Csv -Path $_ should be Import-Csv -Path $_.FullName in your code , Import-Csv -Path $_应该是Import-Csv -Path $_.FullName在你的代码中

    • (Strictly speaking, it should be Import-Csv -LiteralPath $_.FullName , because strings passed to the -Path parameter are subject to wildcard resolution). (严格来说,应该是Import-Csv -LiteralPath $_.FullName ,因为传递给-Path参数的字符串需要进行通配符解析)。
  • because the [System.IO.FileInfo] instances representing files returned by Get-ChildItem are converted to strings when they are passed to the -Path (or -LiteralPath ) parameter as a command-line argument (as opposed to via the pipeline), in which case the the mere file name rather than the full path is used , if your Get-ChildItem command targets a directory in Windows PowerShell (see background information below).因为表示Get-ChildItem返回的文件[System.IO.FileInfo]实例在作为命令行参数(而不是通过管道)传递给-Path (或-LiteralPath )参数时被转换为字符串,在这种情况下,如果您的Get-ChildItem命令以Windows PowerShell 中目录为目标,则使用纯文件名而不是完整路径(请参阅下面的背景信息)。

    • A mere filename such as Book1.csv is interpreted as relative to the current directory (which happened to be C:\\Windows\\system32 in your case), so Import-Csv looks for file C:\\Windows\\system32\\Book1.csv rather than the intended C:\\csv\\Book1.csv .仅文件名(例如Book1.csv被解释为相对于当前目录(在您的情况下恰好是C:\\Windows\\system32 ),因此Import-Csv查找文件C:\\Windows\\system32\\Book1.csv而不是比预期的C:\\csv\\Book1.csv

    • Note that piping Get-ChildItem output to cmdlets is generally not affected by this, because the .PSPath property (which PowerShell adds behind the scenes) containing the full path (including PS provider prefix) binds to the -LiteralPath parameter.需要注意的是管道Get-ChildItem输出的cmdlet一般不会受此影响,因为.PSPath包含完整路径(包括PS提供商前缀)绑定到属性(PowerShell中添加了幕后) -LiteralPath参数。
      Note that as of PSv5.1.14393.693, however, this mechanism is broken for Import-Csv , due to a bug.请注意,从 PSv5.1.14393.693 开始,由于一个错误,这个机制在Import-Csv破坏了。


This is a common pitfall that occurs whenever [System.IO.FileInfo] instances are passed to cmdlets that accept file paths via [string] (-array)-typed parameters as arguments .这是一个常见的陷阱,每当[System.IO.FileInfo]实例传递给通过[string] (-array) 类型参数作为参数接受文件路径的 cmdlet 时,就会发生这种情况。

To be safe: Always use .FullName when you pass objects received from Get-ChildItem to another command as a parameter value (as opposed to via the pipeline) to ensure that the full path is passed.安全起见:当您将从Get-ChildItem接收的对象作为参数值(而不是通过管道)传递给另一个命令时,始终使用.FullName以确保传递完整路径。


Optional background information:可选的背景信息:

This behavior is a pitfall , because it is perfectly reasonable to assume that passing a [System.IO.FileInfo] instance as-is to a command that accepts file paths works, given the object-oriented nature of PowerShell - especially, since it does work reliably when using the pipeline rather than a parameter value.这种行为是一个陷阱,因为假设将[System.IO.FileInfo]实例按原样传递给接受文件路径的命令有效,这是完全合理的,考虑到 PowerShell 的面向对象性质 - 特别是,因为它确实使用管道而不是参数值时可靠地工作。

Unfortunately, the built-in cmdlets that accept file paths ( -Path , -LiteralPath parameters) do so as [string] s only (there is no parameter set that accepts [System.IO.FileInfo] instances directly), and it is in the course of [System.IO.FileInfo] -to-string conversion that the problem arises.不幸的是,接受文件路径( -Path-LiteralPath参数)的内置 cmdlet 仅作为[string] s(没有直接接受[System.IO.FileInfo]实例的参数集),并且它在[System.IO.FileInfo] -to-string 转换过程中出现问题。

There also wouldn't be a problem if the [System.IO.FileInfo] instances consistently evaluated to the files' full paths , which is unfortunately not the case in Windows PowerShell (this has since been fixed in PowerShell Core ):如果[System.IO.FileInfo]实例一致评估为文件的完整路径,也不会出现问题,不幸的是, Windows PowerShell 中并非如此(此问题已在 PowerShell Core 中修复):

  • Get-ChildItem <directory> outputs [System.IO.FileInfo] instances that evaluate to file names only in a string context. Get-ChildItem <directory>输出在字符串上下文中评估为文件名的[System.IO.FileInfo]实例。

  • Get-ChildItem <literalFilePathOrWildCardExpr> outputs [System.IO.FileInfo] instances that evaluate to full paths . Get-ChildItem <literalFilePathOrWildCardExpr>输出评估为完整路径的[System.IO.FileInfo]实例。

In other words: It is only if Get-ChildItem targets a directory (folder) that the objects it returns evaluate to their file names only in a string context.换句话说:只有当Get-ChildItem目录(文件夹)为目标时,它返回的对象才仅在字符串上下文中评估其文件
Targeting a specific file or using a wildcard expression results in full paths, by contrast;相比之下,针对特定文件或使用通配符表达式会产生完整路径; with Get-Item , that's always the case.使用Get-Item ,情况总是如此。

You simply need to 'fullname' property, instead of 'name'.您只需要“全名”属性,而不是“姓名”。

Ex:前任:

PS /Users/adil/Downloads> gi *csv |select name                                                                  

Name              
----              
tradesdownload.csv


PS /Users/adil/Downloads> gi *csv |select name, fullname                                                                

Name               FullName                                
----               --------                                
tradesdownload.csv /Users/adil/Downloads/tradesdownload.csv

try this code.试试这个代码。 This code take all csv file, import them and take only column 1, 2, 3 and change column name to header1, header2, header3, then export all into new csv file此代码获取所有 csv 文件,导入它们并仅获取第 1、2、3 列并将列名更改为 header1、header2、header3,然后全部导出到新的 csv 文件中

Get-ChildItem "C:\temp2" -Filter "*.csv" | 
    %{Import-Csv $_.FullName -Header header1, header3,header4} | 
                    Export-Csv "c:\temp\result.csv" -NoTypeInformation


#a short version (for no purist)
gci "C:\temp2" -Filter "*.csv" | %{ipcsv $_.FullName -Header header1, header3,header4} | epcsv "c:\temp\result.csv" -NoType

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Powershell / Perl:将多个CSV文件合并为一个? - Powershell / Perl : Merging multiple CSV files into one? 使用 PowerShell 将多个 CSV 文件合并为一个文件 - Merging multiple CSV files into one using PowerShell 根据powershell中的大小将一个大的csv文件拆分为多个csv文件 - Split a large csv file into multiple csv files according to the size in powershell 从CSV文件中删除多个文件或文件夹,这些文件或文件夹包含多列(Powershell) - Delete multiple files or folders from a CSV file that contain more than one columns (Powershell) 如何将多个文本文件(特定行+元数据)组合成一个.txt或.csv文件和PowerShell? - How can I combine multiple text files (specific line + metadata) into one .txt or .csv file with PowerShell? 如何使用PowerShell将多个文本文件的列合并到一个csv文件中? - How to merge colums of multiple text files into one csv file using PowerShell? PowerShell - 将多个 CSV 文件导入多个工作表中的 Excel 文件 - PowerShell - Import multiple CSV files to Excel file in multiple worksheets Powershell 脚本将多个 csv 文件合并为一个文件 - Powershell script to combine multiple csv files to single one 使用powershell将多个csv文件转换为xlsx文件但不同的工作表 - Multiple csv files into a xlsx file but different sheets using powershell 连接多个变量/ CSV并导出为一个CSV文件Powershell - Concatenate multiple Variables/CSVs and export as one CSV file Powershell
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM