🐾

PowerShellでユニークなファイル名を作る

2025/01/03に公開

ファイルのコピーとか移動で上書きできないときに括弧付けるアレ
業務系だと日付時刻でどーにでもなるんだけどタマに必要になるんだよなぁと
まぁとりあえず道具箱に放り込んどこかー

本題

function GenUniqName {
    param (
        [string] $Path, 
        [bool]   $isDir
    )
    begin {}
    process {
        $sUniq = $Path
        $lUniq = 1
        while( (Test-Path -LiteralPath $sUniq) ) {
            if ($isDir) {
                $dname = [System.IO.Path]::GetDirectoryName($Path)
                $fname = [System.IO.Path]::GetFileName($Path)
                $ename = ""
            } else {
                $dname = [System.IO.Path]::GetDirectoryName($Path)
                $fname = [System.IO.Path]::GetFileNameWithoutExtension($Path)
                $ename = [System.IO.Path]::GetExtension($Path)
            }
            $sUniq = [System.IO.Path]::Combine($dname, $fname + " ($lUniq)" + $ename)
            $lUniq++
        }
        return $sUniq
    }
    end {}
}

説明

バカがフォルダ名に日付付けると2025.01.03とかやる事を考えると
括弧付き数字の挿入位置を決めるのが割とイヤラシイ感じになるんですよねー
あとバージョン番号のついたフォルダとか

Discussion