4
5

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 3 years have passed since last update.

PowerShellでディレクトリ比較(Compare-Object)

Posted at

PowerShellでディレクトリ間の diff をしてみたかった。ちなみにPowerShellで diff と言えば、 Compare-Object の別名です。

ディレクトリ下のファイル構成比較

一方のディレクトリのみに存在するファイルの有無を確認する。
まず対象フォルダ、比較用の参照フォルダのフルパスをそれぞれ変数に格納しておく。

$targetDir = 'C:/new'
$refDir = 'C:/old'

対象フォルダ内のファイルリストを相対パスで取得。ファイルの取得にGet-ChildItemを、相対パスへの変換にResolve-Pathを使う。カレントディレクトリからの相対パスになるので、対象フォルダに移動してから左記を行う。

Set-Location $targetDir
$targetFiles = Get-ChildItem -File -Recurse | Resolve-Path -Relative

参照フォルダ内のファイルリストを相対パスで取得。

Set-Location $refDir
$refFiles = Get-ChildItem -File -Recurse | Resolve-Path -Relative

比較。Compare-Objectを使う。

Compare-Object $targetFiles $refFiles

ディレクトリ下の各ファイル内容の比較

両方のディレクトリのファイル内容を比較する。
まず対象フォルダ、比較用の参照フォルダのフルパスをそれぞれ変数に格納しておく。

$targetDir = 'C:/new'
$refDir = 'C:/old'

対象フォルダ内のファイルリストを相対パスで取得。

Set-Location $targetDir
$targetFiles = Get-ChildItem -File -Recurse | Resolve-Path -Relative

相対パスを参照対象フォルダ下のファイル群の絶対パスに変換する。結果は対象ファイルと対応が付くように、ハッシュ $refFiles に格納しておく。

Push-Location $refDir
$refFiles = @{}
$targetFiles | %{ $refFiles[$_] = Resolve-Path $_ }
Pop-Location

比較。 $targetDir で実行する必要があるが、すでに Pop-Location により戻ってきているはず。

$targetFiles | %{ Write-Host $_; Compare-Object @(Get-Content $_) @(Get-Content $refFiles[$_]) | ft }

終わりに

ファイル構成に差分があると「ディレクトリ下の各ファイル内容の比較」の「相対パスを参照対象フォルダ下のファイル群の絶対パスに変換する」ところでエラーになるかもしれない。いまは困らないので、保留というか将来に積み残しておく。

4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?