Skip to content

Instantly share code, notes, and snippets.

@josy1024
Created July 7, 2023 04:08
Show Gist options
  • Save josy1024/c72d11bbaa5fe92d6a8fbb583d36b431 to your computer and use it in GitHub Desktop.
Save josy1024/c72d11bbaa5fe92d6a8fbb583d36b431 to your computer and use it in GitHub Desktop.
rename files to leading zeros recurse current path
# rename files recurse to leading 2 digit zeros:
# from "1 - name.mp3"
# to 01 - name.mp3
$path = Get-Location
$files = Get-ChildItem -Path $path -Filter "*.mp3" -recurse | Sort-Object
foreach ($file in $files) {
$nameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($file.Name)
$extension = [System.IO.Path]::GetExtension($file.Name)
$counter = $nameWithoutExtension -replace '^(\d+).*', '$1'
$paddedCounter = '{0:d2}' -f [int]$counter
$nameWithoutDigits = $nameWithoutExtension -replace '^\d+\s*-\s*'
$newName = "$paddedCounter - $nameWithoutDigits$extension"
Write-Host "Aktueller Dateiname: $($file.Name)"
Write-Host "Neuer Dateiname: $newName"
$newPath = Join-Path -Path $file.DirectoryName -ChildPath $newName
Rename-Item -Path $file.FullName -NewName $newPath
#Rename-Item -Path $file.FullName -NewName $newPath -WhatIf
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment