I've been trying to achieve a more consistent file naming scheme and chose PowerShell to help with the task. However, for some reason I can't get the script to replace multiple patterns with underscores.
$regex = [regex] '^\d{4}\d{2}\d{2}_' # $special = [regex] '\. - ' # prepend with date get-childitem -attributes !directory+!system | where-object { !($_.name -match $regex) } | rename-item -newname { (get-date $_.creationtime -format "yyyyMMdd_") + $_.basename + $_.extension } # make all letters lowercase get-childitem -attributes !directory+!system | %{ $newFilename = ($_.basename.tolower())+($_.extension.tolower()); move-item $_ $newFilename } # replace special chars w underscores get-childitem -attributes !directory+!system | where-object { $_.basename.contains(" ") -or $_.basename.contains("-") -or $_.basename.contains(" ") -or $_.basename.contains(".") } | rename-item -newname { $_.basename -replace "\s+-\s+", "_" -replace "-+", "_" -replace "\.+", "_" -replace "\s+", "_" + $_.extension } The first two blocks work fine, but the -replace statements get ignored, and nothing gets replaced with underscores. I've searched around here and on Google, but I couldn't find a fix that works.
I've also tried with this variation:
$_.basename.replace(".", "_") + $_.extension; $_.basename.replace(" ", "_") + $_.extension ... instead of regex, but that messes up file extensions when it gets to the "." part. It also only works on the first pattern ignoring the rest.
$_basename.contains...can be replaced withWhere-Object{ $_.basename -match ' |-|\.' }