Merging multiple CSV files into one using PowerShell

后端 未结 11 1547
慢半拍i
慢半拍i 2020-11-27 17:47

Hello I\'m looking for powershell script which would merge all csv files in a directory into one text file (.txt) . All csv files have same header which is always stored in

11条回答
  •  有刺的猬
    2020-11-27 18:18

    This will append all the files together reading them one at a time:

    get-childItem "YOUR_DIRECTORY\*.txt" 
    | foreach {[System.IO.File]::AppendAllText
     ("YOUR_DESTINATION_FILE", [System.IO.File]::ReadAllText($_.FullName))}
    
    # Placed on seperate lines for readability
    

    This one will place a new line at the end of each file entry if you need it:

    get-childItem "YOUR_DIRECTORY\*.txt" | foreach
    {[System.IO.File]::AppendAllText("YOUR_DESTINATION_FILE", 
    [System.IO.File]::ReadAllText($_.FullName) + [System.Environment]::NewLine)}
    

    Skipping the first line:

    $getFirstLine = $true
    
    get-childItem "YOUR_DIRECTORY\*.txt" | foreach {
        $filePath = $_
    
        $lines =  $lines = Get-Content $filePath  
        $linesToWrite = switch($getFirstLine) {
               $true  {$lines}
               $false {$lines | Select -Skip 1}
    
        }
    
        $getFirstLine = $false
        Add-Content "YOUR_DESTINATION_FILE" $linesToWrite
        }
    

提交回复
热议问题