Windows PowerShell で ファイルを最終更新日で仕分け

久々にPowerShellネタ。
ファイルを最終更新日フォルダへ振分けるスクリプトを書いてみた。

move_files.ps1

#カレントディレクトリ以下(再帰)のファイルについて、下記マップを生成します。
# 更新日yyyyMMdd -> @(file_obj1, file_obj2, ..)
Function Get-Date2FilesMap() {
    $local:date2FilesMap = @{}
    foreach($local:file in (ls -R | ?{ $_.GetType().Name -eq "FileInfo" })) {
    	$local:date = $file.LastWriteTime.ToString('yyyyMMdd')

    	if(! $date2FilesMap.Contains($date)) {
    		$date2FilesMap.Add($date, @())
    	}

    	$date2FilesMap[$date] += $file
    }
    return $date2FilesMap
}

#ディレクトリが存在するかを確認し、存在しない場合は生成します。
#引数:対象のパス文字列
Function Create-IfNotExist($path) {
    if(!(Test-Path $path)) {
        New-Item -Type Directory -Path $path
    }
}

Function Get-TargetDateDirPath($targetDirPath, $date) {
    return ($targetDirPath + "/" + $date)
}

#以下のディレクトリ構成を生成します。
#  カレントディレクトリ
#    target
#      yyyyMMdd
#引数:文字列(yyyyMMdd)配列
Function Create-TargetDirs($targetDirPath, $dates) {   
    Create-IfNotExist $targetDirPath

    foreach($local:date in $dates) {
        Create-IfNotExist (Get-TargetDateDirPath $targetDirPath $date)
    }
}

#移動先のファイルが存在するかを確認し、存在しない場合は移動します。
#引数:移動元パス文字列
#    移動先パス文字列
Function Move-IfNotExist($fromPath, $toPath) {
    if(!(Test-Path $toPath)) {
        Move-Item $fromPath $toPath
    }
}

#最終更新日のフォルダへファイルを移動します。
Function Move-Files($targetDirPath, $date2FilesMap) {
    foreach($local:key in $date2FilesMap.Keys) {
        foreach($local:file in $date2FilesMap[$key]) {
            Move-IfNotExist $file.FullName ((Get-TargetDateDirPath $targetDirPath $key) + "/" + $file.Name)
        }
    }
}

Function main() {
    $local:date2FilesMap = Get-Date2FilesMap
    
    $local:targetDirPath = "./target"
    Create-TargetDirs $targetDirPath $date2FilesMap.Keys
    Move-Files $targetDirPath $date2FilesMap
}

main

実行例

前提
move_files.ps1
カレントディレクトリ
 ディレクトリ1
  写真ファイル1−1(2013/6/1更新)
  写真ファイル1−2(2013/6/2更新)
 ディレクトリ2
  写真ファイル2−1(2013/6/1更新)
  写真ファイル2−2(2013/6/2更新)
実行
powershell -File ../move_files.ps1
結果
move_files.ps1
カレントディレクトリ
 ディレクトリ1
 ディレクトリ2
 target
  20130601
   写真ファイル1−1(2013/6/1更新)
   写真ファイル2−1(2013/6/1更新)
  20130602
   写真ファイル1−2(2013/6/2更新)
   写真ファイル2−2(2013/6/2更新)