我有几千个文件名分隔:
Last, First-000000-Title-MonYYYY.pdf
Probem 1:某些文件符合6位数约定,而其他文件需要前导零以保持一致性。
问题2:有些名称是用破折号输入的(有问题的是分隔符)需要连接起来: Last-Last,First> LastLast,First
我能够为每个文件执行简单的Rename-Item
函数,但是无法创建更广泛的Get-ChildItem
函数,同时考虑到文件名的多次迭代以生成一致输出
为入门级问题道歉,但我似乎无法将所需的功能连贯地汇总在一起。
答案 0 :(得分: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
如果有更复杂的案例,可能无效。