0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowerShellで再帰的にCSVファイルをマージする

Posted at

複数CSVのマージ

全ファイル同一フォーマットでヘッダーありの例

Invoke-MargeCSV.ps1
param (
    [parameter(mandatory=$true)][string]$Path
)
$heder = "ID","column1","column2","column3","column4","column5"
Get-ChildItem -Path $Path -Recurse -Filter "*.csv" | %{ Import-Csv -Path $_.FullName -Header $heder | Select-Object -Skip 1 } | Export-Csv -Encoding UTF8 -Path .\test.csv -NoClobber -NoTypeInformation

行別解説

1~3行目:探索対象のトップフォルダを指定

必須の引数として、再帰的に探索するトップのフォルダを指定できるようにしています。

param (
    [parameter(mandatory=$true)][string]$Path
)

$Path 変数にパスを直書きでもOK

$Path = "C:\Users\myUser\Desktop"

4行目:CSVのヘッダーを指定

ヘッダーを文字列配列として指定しています。
ヘッダーなしの場合は不要

$heder = "ID","column1","column2","column3","column4","column5"

5行目の1パイプ目の処理:再帰的に拡張子.csvのファイルを配列で取得

大文字小文字は区別されないため、.csv または .CSV いずれかを指定します。

Get-ChildItem -Path $Path -Recurse -Filter "*.csv" 

.txtを含めたくなったときは以下の様に指定する。
-Filter-Include に変更しています。

Get-ChildItem -Path $Path -Recurse -Include "*.csv","*.txt" 

5行目の2パイプ目の処理:1ファイルずつCSVファイルの中身を読み込み

Get-ChildItem で取得したファイル名のフルパスと$hederで指定したヘッダーを利用し
CSVファイルの読み込みを行います。
(全てにヘッダー行が指定されている場合、Select-Object -Skip 1 で1行目(ヘッダー行)をスキップする。)

%{ Import-Csv -Path $_.FullName -Header $heder | Select-Object -Skip 1 }

5行目の3パイプ目の処理:CSVファイルの中身を書き込み

-Encodingで文字コードを指定
-Pathで出力パスを指定
-NoClobberで上書きを禁止(誤って上書かないように)
-NoTypeInformationで不要なCSVの補足データが出力されないように指定

Export-Csv -Encoding UTF8 -Path .\test.csv -NoClobber -NoTypeInformation
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?