Единые имена файлов
Приводит имена файлов к шаблону с датой и безопасным названием, показывая предпросмотр.
Что делает скрипт
Скрипт формирует новые имена по шаблону с полями date, name и ext, заменяет недопустимые символы и проверяет конфликты. По умолчанию выполняется только предпросмотр, а для переименования нужен флаг Apply. Системные и скрытые файлы пропускаются.
- Переименование меняет пути. Сначала проверьте предпросмотр и сделайте резервную копию.
Быстрый старт
powershell -File Rename-ByPattern.ps1 -Path C:\Users\user\Documents -Pattern "{date}_{name}"
Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.
Другие варианты
powershell -File Rename-ByPattern.ps1 -Path C:\Users\user\Documents -Pattern "{date}_{name}"powershell -File Rename-ByPattern.ps1 -Path C:\Users\user\Downloads -Pattern "{name}_{date}" -Applypowershell -File Rename-ByPattern.ps1 -Path . -Pattern "{date}_{name}" -Lower -Apply
Что понадобится
Встроен в Windows 10/11 (PowerShell 5.1)
Rename-ByPattern.ps1
[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"
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.