Skip to content

Instantly share code, notes, and snippets.

@milesgratz
Last active April 23, 2017 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milesgratz/8fd0193b3301111532a208ca0095563f to your computer and use it in GitHub Desktop.
Save milesgratz/8fd0193b3301111532a208ca0095563f to your computer and use it in GitHub Desktop.
Replace non-alphanumeric characters in folder of files
# Potential input
# -------------------------------------
# Test File With Spaces.txt
# Test_File_With_Underscores.txt
# Weird_Chars##$%@1.txt
$badFiles = Get-ChildItem "C:\temp\irregular files"
foreach ($file in $badFiles)
{
# Check for file extension
$fileExt = (Split-Path -Path $file.Name -Leaf).Split(".")[1]
# Regex match any non-alphanumeric characters
$fileNewName = ($file.BaseName -replace "[^a-zA-Z0-9 :]") + $fileExt
Try { Rename-Item $file.FullName -NewName $fileNewName }
Catch { $_ }
}
# Output
# -------------------------------------
# Test File With Spaces.txt
# TestFileWithUnderscores.txt
# WeirdChars1.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment