Can anyone tell me if they think there is something wrong with this Powershell script.
Dir |
where {$_.extension -eq ".txt"} |
Rename-Item –NewName { $_.name –replace “.“,”-” }
For each text file in the current directory, I'm trying to replace all periods in the file names with hyphens. Thanks ahead of time.
As the others have said, -replace uses regex (and "." is a special character in regex). However, their solutions are forgetting about the fileextension and they are acutally removing it. ex. "test.txt" becomes "test-txt" (no extension). A better solution would be:
dir -Filter *.txt | Rename-Item -NewName { $_.BaseName.replace(".","-") + $_.Extension }
This also uses -Filter to pick out only files ending with ".txt" which is faster then comparing with where.
-replace operates on regex, you need to escape '.':
rename-item -NewName { $_.Name -replace '\.', '-' }
Otherwise you will end up with '----' name...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With