maisonfinder
maisonfinder

Reputation: 23

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.

Upvotes: 2

Views: 6738

Answers (2)

Abraham Zinala
Abraham Zinala

Reputation: 4694

Get-ChildItem -Path C:\ -File | ForEach {Rename-Item $_.FullName -NewName ($_.name).Replace(".txt",".csv")}

Using dot notation, it reads characters as such; meaning no need in escaping any special chars.

Upvotes: 0

Mark Elvers
Mark Elvers

Reputation: 647

-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" }

Upvotes: 5

Related Questions