简体   繁体   中英

Renaming files with incremented number in the middle of the name using powershell

I've searched long and hard for this, but cannot seem to locate a means of completing the renaming of files within multiple directories. The issue is that I need to insert a unique number sequence in the middle of a file name. Here are the examples of my file names:

8675309_FileName1_ExtraSuff1_Extrastuff2 and some more stuff_012345.html
2020202_FileName2_ExtraSuff1_Extrastuff2 and some more stuff_012345.html
... etc.

Renamed to insert a copy of the 1st 7 fields, a numeric sequencing and a date as in the following:

8675309_8675309_00001_2022_FileName1_ExtraSuff1_Extrastuff2 and some more stuff_012345.html
2020202_2020202_00002_2022_FileName2_ExtraSuff1_Extrastuff2 and some more stuff_012345.html
... etc.

Here is what I've tried so far:

$i = 1 Get-ChildItem -Filter *.html | ForEach-Object{ Rename-Item -Path $ .FullName -NewName (($ .BaseName -split ' ')[0] + ' ' + ('{0:D5}' -f $i) + ' 2022' + ' Performance_Eval ' + ($ .BaseName -split ' ')[1] + ($ .BaseName -split ' ')[2] + ($ .BaseName -split ' ')[3] + ' ' + ($ .BaseName -split ' ')[4] + $_.Extension ) $i++ }

This gives me most of what I need, but not the additional first 7 characters:

8675309_00001_2022_FileName1_ExtraSuff1_Extrastuff2 and some more stuff_012345.html

Ho can I tweak this script to bring in the initial characters?

Since your file names seem to have a structure or a unique character you can split them on you could use something like this:

$i = 1 
Get-ChildItem -Filter *.html | 
ForEach-Object{
    $SplitName = $_.BaseName -split '_'
    $NewName = ((@($SplitName[0]) * 2) -join '_') + '_' + ('{0:D5}' -f $i) + '_2022' + ($SplitName[1..($SplitName.Length -1)] -join '_') + $_.Extension 
    Rename-Item -Path $_.FullName -NewName $NewName
    $i++
}

I'm curious: why do you need the same sequence of numbers twice?

This worked perfectly! Thank you for the help, Olaf.

In terms of the multiples, it was as a result of the file being used as a read into a batch upload. The original name wasn't able to be used with our utility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM