用于重命名文件的Powershell脚本

时间:2013-02-24 08:51:41

标签: powershell powershell-v3.0

我有一堆文件,其名称以数字开头,可能在两个数字之一后包含空格和破折号,然后有时(有时不会)在我要保留的名称的第一个字母字符之前有一个空格,即:

2-01 Dazed And Confused.txt(我想将其重命名为Dazed And Confused.txt)

或者

02 - Uncle Salty.txt(我想将其重命名为Uncle Salty.txt)

02-Night Before.txt(我想重命名为The Night Before.txt)

3 个答案:

答案 0 :(得分:6)

Move-ItemRename-Item cmdlet可以直接从管道接受源,并使用脚本块提供新名称:

dir | Move-Item -Destination { $_.Name -replace '^([0-9\-\s]*)' }

dir | Rename-Item -NewName { $_.Name -replace '^([0-9\-\s]*)' }

答案 1 :(得分:4)

dir c:\tmp | % {
     mv $_.FullName $(Join-Path $_.Directory ($_.Name -replace "^([0-9\-\s]*)",'').Trim());
}

如果您需要递归处理YourDirectory,请在-recurse之后添加dir

答案 2 :(得分:0)

尝试这样的事情:

$re = '^\d+\s*-\d*\s*(.*)$'
$recurse = $false

Get-ChildItem "C:\some\folder" -Recurse:$recurse | ? {
  -not $_.PSIsContainer -and $_.Name -match $re
} | % {
  Move-Item $_.FullName (Join-Path $_.Directory $matches[1])
}

如果您希望连字符是可选的,请将正则表达式更改为'^\d+\s*-?\d*\s*(.*)$'

如果您想要递归到子文件夹,请将$recurse更改为$true