PowerShellでファイルの拡張子を大文字にする
動機
写真の整理する際、拡張子の大文字/小文字が変わってしまった。これを元に戻したかった。
ソースコード
$dirs = @( ) $debug = $false $whatif = @{} if($debug) { $whatif["whatif"] = $Null } function GetRenameInfo($obj) { $fullpath = $obj.Fullname $ext = $obj.Extension.ToUpper() $newname = [System.IO.Path]::GetFileNameWithoutExtension($fullpath) + $ext $newpath = Join-Path -Path (Split-Path $fullpath) -ChildPath $newname return ,@($fullpath, $newpath) } foreach($dir in $dirs) { gci $dir | %{ GetRenameInfo $_ } | %{ move-item -LiteralPath $_[0] -Destination $_[1] @whatif } }
追記:
whatif オプションについては $WhatIfPreference という変数で挙動が変えられるようです。また -whatif:$false という書き方もできるようです。
$dirs = @( ) $WhatIfPreference = 1 function IsTarget($obj) { (Test-Path $obj -PathType Leaf) -and ($obj.Extension -cne $obj.Extension.ToUpper()) } function GetRenameInfo($obj) { $fullpath = $obj.Fullname $ext = $obj.Extension.ToUpper() $newname = [System.IO.Path]::GetFileNameWithoutExtension($fullpath) + $ext $newpath = Join-Path -Path (Split-Path $fullpath) -ChildPath $newname return @{SRC=$fullpath; DST=$newpath} } function ExtensionToUpperInADirectiory($dir) { gci $dir | ?{ IsTarget $_ } | %{ GetRenameInfo $_ } | %{ move-item -LiteralPath $_.SRC -Destination $_.DST } } foreach($dir in $dirs) { ExtensionToUpperInADirectiory $dir }