[CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$Path, [string]$Format = 'yyyy-MM-dd', [string]$Filter = '*', [switch]$Recurse, [switch]$Apply ) $ErrorActionPreference = 'Stop' if ($Format -match '[\\/]') { throw 'Format must not contain path separators.' } if (-not (Test-Path -LiteralPath $Path -PathType Container)) { throw "Folder not found: $Path" } $root = (Resolve-Path -LiteralPath $Path).Path if ($Recurse) { $items = @(Get-ChildItem -LiteralPath $root -File -Filter $Filter -Recurse -ErrorAction SilentlyContinue) } else { $items = @(Get-ChildItem -LiteralPath $root -File -Filter $Filter -ErrorAction SilentlyContinue) } if ($items.Count -eq 0) { Write-Host 'No files found.' exit 0 } $planned = 0 foreach ($file in $items) { $datePrefix = $file.LastWriteTime.ToString($Format) if ($file.Name.StartsWith($datePrefix + '_')) { continue } $newName = $datePrefix + '_' + $file.Name $target = Join-Path -Path $file.DirectoryName -ChildPath $newName if (Test-Path -LiteralPath $target) { Write-Warning "Skip, target exists: $target" continue } if ($Apply) { Rename-Item -LiteralPath $file.FullName -NewName $newName -ErrorAction Stop Write-Host "Renamed: $($file.Name) -> $newName" } else { Write-Host "Preview: $($file.Name) -> $newName" } $planned++ } if (-not $Apply) { Write-Host "Preview: $planned file(s). Add -Apply to rename." }