Найти старые аудиозаписи
Показывает записи старше заданного срока и переносит их в архив только с флагом Apply.
Что делает скрипт
Скрипт ищет аудиофайлы по дате изменения и сначала выводит список кандидатов. Перемещение в отдельную папку выполняется только при явном флаге Apply, файлы не удаляются. Структура подпапок сохраняется.
- Перемещение выполняется только с флагом Apply. Удаления нет.
Быстрый старт
powershell -File Move-OldRecordings.ps1 -Path C:\Recordings -Days 180
Скачайте файл, откройте терминал в папке со скриптом и выполните команду. Запускайте в PowerShell 5.1 или PowerShell 7.
Другие варианты
powershell -File Move-OldRecordings.ps1 -Path D:\Voice -Days 90 -Applypowershell -File Move-OldRecordings.ps1 -Path C:\Music -Days 365 -ArchiveDirectory D:\Archive
Что понадобится
Встроен в Windows 10/11 (PowerShell 5.1)
Move-OldRecordings.ps1
[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)]
[string]$Path,
[ValidateRange(1, 3650)]
[int]$Days = 90,
[string]$ArchiveDirectory,
[switch]$Apply
)
$ErrorActionPreference = 'Stop'
$resolved = Resolve-Path -LiteralPath $Path -ErrorAction Stop
$extensions = @('.mp3', '.wav', '.flac', '.ogg', '.m4a', '.aac', '.wma', '.opus')
$singleFile = $null
if (Test-Path -LiteralPath $resolved.Path -PathType Container) {
$root = $resolved.Path
} else {
$item = Get-Item -LiteralPath $resolved.Path
if ($extensions -notcontains $item.Extension.ToLowerInvariant()) {
throw "Формат не похож на аудио: $($item.Extension)"
}
$singleFile = $item
$root = Split-Path -Parent $item.FullName
}
$cutoff = (Get-Date).AddDays(-$Days)
if ($singleFile) {
$files = @($singleFile | Where-Object { $_.LastWriteTime -lt $cutoff })
} else {
$files = @(Get-ChildItem -LiteralPath $root -File -Recurse -ErrorAction SilentlyContinue |
Where-Object {
$extensions -contains $_.Extension.ToLowerInvariant() -and
$_.LastWriteTime -lt $cutoff
} | Sort-Object LastWriteTime)
}
if ($files.Count -eq 0) {
Write-Host "Записей старше $Days дней не найдено."
exit 0
}
if (-not $ArchiveDirectory) {
$ArchiveDirectory = Join-Path $root 'archive-old'
}
$archiveRoot = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($ArchiveDirectory)
Write-Host "Кандидатов: $($files.Count), старше $Days дней (до $($cutoff.ToString('yyyy-MM-dd')))"
$moved = 0
$skipped = 0
foreach ($file in $files) {
$relative = $file.FullName.Substring($root.Length).TrimStart([char[]]@([char]'\', [char]'/'))
$destination = Join-Path $archiveRoot $relative
Write-Host ("{0:yyyy-MM-dd} {1}" -f $file.LastWriteTime, $file.FullName)
if (-not $Apply) { continue }
if (Test-Path -LiteralPath $destination) {
Write-Host "Пропуск: $destination уже существует"
$skipped++
continue
}
if (-not $PSCmdlet.ShouldProcess($file.FullName, "Переместить в $destination")) { continue }
$parent = Split-Path -Parent $destination
New-Item -ItemType Directory -Path $parent -Force | Out-Null
Move-Item -LiteralPath $file.FullName -Destination $destination
$moved++
}
if (-not $Apply) {
Write-Host 'Это предпросмотр. Для перемещения добавьте -Apply.'
} else {
Write-Host "Итог: перемещено $moved, пропущено $skipped"
}
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.