2015-07-10 52 views
-2

我有幾千個文件名分隔爲這樣:使用重命名,編號,使數字標識符與一致的名稱

Last, First-000000-Title-MonYYYY.pdf 

Probem 1:有些文件符合6位數的約定,而其他需要的一致性前導零。

問題2:一些名稱與輸入破折號(這是,問題在於,分隔符),其需要被加入成爲這樣: LastLast,首先> LastLast,首先

我能夠執行簡單Rename-Item函數爲每個文件,但無法創建一個更廣泛的Get-ChildItem功能考慮到文件名的幾次迭代生成一致的輸出。

對入門級的問題抱歉,但我似乎無法一致地將所需的功能彙總在一起。

回答

0

根據您的解釋:

Set-Location -Path "C:\path" # replace this with actual path to where the files are 

$cFiles = Get-ChildItem -Filter "*.pdf" # Getting all PDFs in the folder 

foreach ($oFile in $cFiles) { 
    $sName = $oFile.Name 
    # This regex captures 1-5 digits number between two dashes. 
    $sPattern = '(?:(?<=-))(\d{1,5})(?:(?=-))' 
    if ($sName -match $sPattern) { 
     # Extracting number. 
     [UInt32]$iNumber = $sName -replace (".*" + $sPattern + ".*"), '$1' 
     # Padding number with zeros. 
     $sNumber = "{0:D6}" -f $iNumber 
     # Updating filename string. 
     $sName = $sName -replace $sPattern, $sNumber 
    } else { 
     # This regex captures 6 digits number between two dashes. 
     $sPattern = '.*-(\d{6})-.*' 
     # Extracting number. 
     $sNumber = $sName -replace $sPattern, '$1' 
    } 

    # Splitting filename string on 6 digits number. 
    $cParts = $sName -split $sNumber 
    # Removing dashes from first/last names and re-assembling filename string. 
    $sName = ($cParts[0] -replace '-') + '-' + $sNumber + $cParts[1] 

    Rename-Item -Path $oFile.Name -NewName $sName 
} 

測試在下面的示例:如果有更復雜的情況

Last, First-000000-Title-Jan1900.pdf 
One-Two, Three-123-Title-Feb2000.pdf 
Four, Five-Six-456-Title-Mar2010.pdf 
Seven-Eight, Nine-Ten-7890-Title-Sep2012.pdf 

可能無法正常工作。

相關問題