Search code examples
powershellfile-extension

Powershell Changing Bulk File Extensions All At Once


Long story short: need to change multiple file extensions that are . (in Windows, the file extension is just a .) to .csv. I am able to do this in command prompt with this:

ren *. *.csv

But when I try to rename in Powershell, it only changes the first file (result: .csv.csv.csv.csv.csv.csv.csv) while the rest of the files remain untouched. I used this command:

Dir | Rename-Item -NewName { $_.name -replace ".",".csv" }

Can someone explain what I'm doing wrong and how come the first file is being renamed as such? Don't understand why Powershell makes it more complicated since it is based off CMD.


Solution

  • -replace is using regular expression matching where . will match any character so every character is replaced with .csv. Try this to replace *.txt and *.file with *.csv

    gci -File | Rename-Item -NewName { $_.name -replace "\.(txt|file)$", ".csv" }
    

    The question has changed. If your files really end in . which I can't actually reproduce then -replace "\.$", ".csv" where \. matches a literal dot and $ matches the end of the line.

    If your files have no extension at all then you could do -replace "$", ".csv"

    Or you could filter for files with no extension and just add one

    gci -File |? Extension -eq ''  |% { Rename-Item $_.FullName -NewName "$($_).csv" }