[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$Path, [string]$Pattern = '{date}_{name}', [switch]$Lower, [switch]$Apply ) $ErrorActionPreference = 'Stop' if (-not (Test-Path -LiteralPath $Path -PathType Container)) { throw "Папка не найдена: $Path" } if (-not $Pattern.Contains('{name}')) { throw 'Шаблон должен содержать {name}.' } $root = (Resolve-Path -LiteralPath $Path).Path $files = @(Get-ChildItem -LiteralPath $root -File -ErrorAction SilentlyContinue) $planned = @() foreach ($file in $files) { if ($file.Name.StartsWith('.')) { continue } if ($file.Attributes -band [System.IO.FileAttributes]::Hidden) { continue } $base = [regex]::Replace($file.BaseName, '[^\p{L}\p{N}._-]+', '-') $base = $base.Trim([char[]]@('-', '.', ' ')) if ([string]::IsNullOrWhiteSpace($base)) { continue } if ($Lower) { $base = $base.ToLowerInvariant() } $newBase = $Pattern.Replace('{date}', $file.LastWriteTime.ToString('yyyy-MM-dd')) $newBase = $newBase.Replace('{name}', $base) $newBase = $newBase.Replace('{ext}', $file.Extension.TrimStart('.')) if ($Pattern.Contains('{ext}')) { $newName = $newBase } else { $newName = $newBase + $file.Extension } $newName = [regex]::Replace($newName, '[\\/:*?"<>|]+', '-').Trim() if ([string]::IsNullOrWhiteSpace($newName) -or $newName -eq $file.Name) { continue } $target = Join-Path $root $newName if (Test-Path -LiteralPath $target) { Write-Warning "Пропуск, файл уже существует: $target" continue } $planned += [pscustomobject]@{ Old = $file.Name; New = $newName; FullName = $file.FullName } } if ($planned.Count -eq 0) { Write-Host 'Нечего переименовывать.' exit 0 } $planned | Format-Table -AutoSize if (-not $Apply) { Write-Host 'Это предпросмотр. Для переименования добавьте -Apply.' exit 0 } $done = 0 foreach ($item in $planned) { $target = Join-Path $root $item.New if (Test-Path -LiteralPath $target) { Write-Warning "Пропуск, файл появился: $target" continue } Rename-Item -LiteralPath $item.FullName -NewName $item.New Write-Host "$($item.Old) -> $($item.New)" $done++ } Write-Host "Переименовано файлов: $done"