# 比較するディレクトリのパス
$sourceDir = "\\172.16.1.137\share"
$destinationDir = "E:\share"
# ログの保存先ディレクトリ
$logDir = "C:\work\log"
# ファイル名に日時を付与
$timestamp = Get-Date -Format "yyyyMMddHHmmss"
$logFile = Join-Path -Path $logDir -ChildPath "ComparisonLog_$timestamp.txt"
# Get-FileHashを使ってファイルのハッシュ値を取得する関数
function Get-FileHashValue {
param (
[string]$filePath
)
if (Test-Path $filePath) {
return (Get-FileHash -Path $filePath -Algorithm SHA256).Hash
}
return $null
}
# ディレクトリのファイル情報を取得する関数
function Get-FileList {
param (
[string]$directory
)
return Get-ChildItem -Path $directory -Recurse -File | ForEach-Object {
[PSCustomObject]@{
Path = $_.FullName.Substring($directory.Length)
Size = $_.Length
Hash = Get-FileHashValue $_.FullName
}
}
}
# コピー元とコピー先のファイル情報を取得
$sourceFiles = Get-FileList -directory $sourceDir
$destinationFiles = Get-FileList -directory $destinationDir
# 比較のためにハッシュテーブルに変換
$sourceFileHashTable = @{}
$sourceFiles | ForEach-Object {
$sourceFileHashTable[$_.Path] = $_
}
$destinationFileHashTable = @{}
$destinationFiles | ForEach-Object {
$destinationFileHashTable[$_.Path] = $_
}
# 結果を格納する変数
$comparisonResults = @()
# ファイルの比較
foreach ($sourceFile in $sourceFiles) {
$path = $sourceFile.Path
if ($destinationFileHashTable.ContainsKey($path)) {
$destinationFile = $destinationFileHashTable[$path]
$comparisonResults += [PSCustomObject]@{
Path = $path
SourceSize = $sourceFile.Size
DestinationSize = $destinationFile.Size
SourceHash = $sourceFile.Hash
DestinationHash = $destinationFile.Hash
Match = ($sourceFile.Size -eq $destinationFile.Size) -and ($sourceFile.Hash -eq $destinationFile.Hash)
}
} else {
$comparisonResults += [PSCustomObject]@{
Path = $path
SourceSize = $sourceFile.Size
DestinationSize = 'Not Found'
SourceHash = $sourceFile.Hash
DestinationHash = 'Not Found'
Match = $false
}
}
}
# 結果をテキストファイルに保存
$comparisonResults | Format-Table -AutoSize | Out-String | Set-Content -Path $logFile
# 不一致があるかどうかを確認する
$differences = $comparisonResults | Where-Object { -not $_.Match }
if ($differences) {
$differences | Format-Table -AutoSize | Out-String | Add-Content -Path $logFile
Write-Host "不一致が見つかりました。詳細はログファイルを参照してください: $logFile" -ForegroundColor Red
} else {
Write-Host "全てのファイルが一致しています。詳細はログファイルを参照してください: $logFile" -ForegroundColor Green
}