如何使用 PowerShell 遍历文件并重命名? [英] How to loop through files and rename using PowerShell?

查看:172
本文介绍了如何使用 PowerShell 遍历文件并重命名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将文件夹中的所有 jpg 文件重命名为统一约定,例如 Picture00000001.jpg,其中 00000001 是计数器.

I would like to rename all the jpg files in a folder to uniform convention like Picture00000001.jpg where 00000001 is a counter.

这将是在 C# 中在公园散步,但我认为这是 PowerShell 的主要用途.

It would be a walk in the park in C# but I would think this is the kind of bread and butter stuff that PowerShell was made for.

我猜是这样的

$files = ls *.jpg
$i=0
foreach($f in $files) { Rename-Item $f -NewName "Picture"+($i++)+".jpg" }

但在我开始讨论之前,我想 1) 格式化计数器,以及 2) 有某种感觉,这实际上是一个好主意.

But before I hit the gas on this I would like to 1) format the counter, and 2) have some sense that this is in fact even a good idea.

如果这听起来更像是强迫症而不是一个好主意,请说出来.

If this sounds more like OCD than a good idea please speak up.

推荐答案

您可以在 PowerShell 中相当简单地执行此操作:

You can do this fairly simply in PowerShell:

ls *.jpg | Foreach -Begin {$i=1} `
   -Process {Rename-Item $_ -NewName ("Picture{0:00000000}.jpg" -f $i++) -whatif}

如果您正在寻找basename"并且如果您使用的是 PowerShell 2.0,只需使用 PowerShell 添加到每个 FileInfo 对象的 Basename 属性:

If you're looking for the "basename" and if you're on PowerShell 2.0 just use the Basename property that PowerShell adds to each FileInfo object:

ls *.jpg | Format-Table Basename

请注意,在 PowerShell 1.0 上,PowerShell Community Extensions 添加了相同的 Basename 属性.

Note that on PowerShell 1.0, the PowerShell Community Extensions adds this same Basename property.

如果目的是在重命名操作期间将计数器字符串附加到文件的基本名称,请尝试以下操作:

If the intent is to append a counter string to the file's basename during the rename operation then try this:

ls *.jpg | Foreach {$i=1} `
   {Rename-Item $_ -NewName ("$($_.Basename){0:00000000#}.jpg" -f $i++) -whatif}

这篇关于如何使用 PowerShell 遍历文件并重命名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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