簡體   English   中英

用於重命名文件的Powershell腳本

[英]Powershell script to rename files

我有一堆文件,其名稱以數字開頭,可能在兩個數字之一后包含空格和短划線,然后有時(有時不會)在我想要保留的名稱的第一個字母字符之前有一個空格,即:

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

要么

02 - Uncle Salty.txt(我想將其重命名為Uncle Salty.txt)

要么

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

Move-ItemRename-Item cmdlet可以直接從管道接受源,並使用腳本塊提供新名稱:

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

要么

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

如果你需要處理遞歸YourDirectory,添加-recursedir

嘗試這樣的事情:

$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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM