Skip to content

Instantly share code, notes, and snippets.

@pleabargain
Created February 3, 2025 10:24
Show Gist options
  • Save pleabargain/66e8eb3594793dc07b0a41cf33e072b0 to your computer and use it in GitHub Desktop.
Save pleabargain/66e8eb3594793dc07b0a41cf33e072b0 to your computer and use it in GitHub Desktop.
powershell to prepend a name to all PDFs in a directory
# Get the current directory
$currentDir = Get-Location
# Get all PDF files in the current directory
$pdfFiles = Get-ChildItem -Path $currentDir -Filter "*.pdf"
# If no PDF files found, inform user and exit
if ($pdfFiles.Count -eq 0) {
Write-Host "No PDF files found in the current directory."
exit
}
# Display all found PDF files
Write-Host "`nFound the following PDF files:`n"
$pdfFiles | ForEach-Object { Write-Host $_.Name }
# Ask for the string to prepend
$prependString = Read-Host "`nEnter the string you want to prepend to the filenames"
# Show preview and ask for confirmation
Write-Host "`nFiles will be renamed as follows:"
$pdfFiles | ForEach-Object {
$newName = "$prependString$($_.Name -replace ' ', '_')"
Write-Host "$($_.Name) -> $newName"
}
$confirmation = Read-Host "`nDo you want to proceed with renaming? (Y/N)"
if ($confirmation -eq 'Y' -or $confirmation -eq 'y') {
# Perform the renaming
$pdfFiles | ForEach-Object {
$newName = "$prependString$($_.Name -replace ' ', '_')"
$newPath = Join-Path $currentDir $newName
Copy-Item $_.FullName -Destination $newPath
Write-Host "Created: $newName"
}
Write-Host "`nRenaming complete! Original files have been preserved."
} else {
Write-Host "`nOperation cancelled. No files were renamed."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment