用Powershell对文件批量重命名

需求:将D盘For PS文件夹下的A.txt文件重命名为aa.txt

rename-Item 'D:\For PS\A.txt' -NewName 'aa.txt'

需求:将D盘For PS文件夹下的所有的txt文件改为html文件,即.txt改为.html

get-childItem 'D:\For PS' *.txt | rename-item -newname { $_.name -replace '\.txt','.html' }

备注:由于replace的模式匹配字符串参数支持正则表达式,’.txt’要转义成’.txt’。

需求:将D盘For PS文件夹下的所有的txt文件加上一个"Test_“的前缀

cd 'D:\For PS'
get-childItem  -r *.txt | rename-Item -newname{'Test_'+$_.name}

如果觉得上面的命令太精简,看不太懂,可以用如下语句,更好理解些:

$dir = dir D:\ForPS *.txt
foreach($_ in $dir)
{
    rename-Item $_.FullName -NewName ('Test_'+$_.Name)
}

将D盘For PS文件夹下的所有的txt文件重命名为 Note1.txt、Note2.txt这样的形式

get-childItem  'D:\For PS' -r  *.txt | foreach-Object -Begin {$count = 1}  -Process{
rename-Item $_.fullname -NewName "Note$count.txt";$count++}

用PowerShell以编程的思想去操作文件,还可以实现更多更复杂的需求。