Created
February 8, 2025 08:05
-
-
Save pleabargain/bda7fa96e2c32eff2e03f5f040a57181 to your computer and use it in GitHub Desktop.
rename a bunch of files, remove white space with powershell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Get all .docx files in the current directory | |
$files = Get-ChildItem -Filter "*.docx" | |
# Check if any files were found | |
if ($files.Count -eq 0) { | |
Write-Host "No .docx files found in the current directory." | |
exit | |
} | |
# Display current files | |
Write-Host "`nCurrent .docx files found:" | |
Write-Host "------------------------" | |
$files | ForEach-Object { Write-Host $_.Name } | |
# Prompt for prefix string | |
Write-Host "`nEnter the string to prepend to the filenames:" | |
$prefix = Read-Host | |
# Clean up the prefix by removing whitespace | |
$prefix = $prefix -replace '\s+', '_' | |
Write-Host "Using prefix: $prefix" | |
# Show preview of new filenames | |
Write-Host "`nNew filenames will be:" | |
Write-Host "--------------------" | |
$newNames = @() | |
foreach ($file in $files) { | |
# Replace whitespace with underscores | |
$cleanName = $file.Name -replace '\s+', '_' | |
$newName = "$prefix$cleanName" | |
$newNames += @{ | |
OldName = $file.Name | |
NewName = $newName | |
} | |
Write-Host "$($file.Name) -> $newName" | |
} | |
# Confirm rename | |
Write-Host "`nDo you want to rename these files? (Y/N)" | |
$confirm = Read-Host | |
if ($confirm.ToUpper() -eq 'Y') { | |
foreach ($item in $newNames) { | |
try { | |
Rename-Item -Path $item.OldName -NewName $item.NewName -ErrorAction Stop | |
Write-Host "Renamed: $($item.OldName) -> $($item.NewName)" -ForegroundColor Green | |
} | |
catch { | |
Write-Host "Error renaming $($item.OldName): $_" -ForegroundColor Red | |
} | |
} | |
Write-Host "`nFile rename operation completed." | |
} | |
else { | |
Write-Host "`nFile rename operation cancelled." | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment