Powershell一次更改批量文件扩展名 [英] Powershell Changing Bulk File Extensions All At Once

查看:120
本文介绍了Powershell一次更改批量文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长话短说:需要更改多个文件扩展名.(在Windows中,文件扩展名只是.)到.csv.我可以在命令提示符下执行以下操作:

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

但是当我尝试在Powershell中重命名时,它只会更改第一个文件(结果: .csv.csv.csv.csv.csv.csv.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" }

有人可以解释我做错了什么,为什么第一个文件被这样重命名?不知道Powershell为何基于CMD使其变得更加复杂.

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.

推荐答案

-replace 使用正则表达式匹配,其中.将匹配任何字符,因此将每个字符替换为 .csv .尝试用 *.csv

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

问题已更改.如果您的文件确实以我无法真正复制的.结尾,则-替换"\.$",.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.

如果文件根本没有扩展名,则可以-替换"$",.csv"

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

这篇关于Powershell一次更改批量文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆