Home > front end >  Batch rename files and organize them Bat Script
Batch rename files and organize them Bat Script

Time:10-04

Friends, I need to rename pdf files to a certain standard. For that I made the following script:

c:

cd \importation

if not exist %1 goto end
md %~n1 
move %1 %~n1\P%~n1_V1_A0V0_T07-54-369-664_S00001_Volume.pdf 

if not exist %2 goto end
md %~n2 
move %2 %~n2\P%~n2_V1_A0V0_T07-54-369-664_S00001_Volume.pdf 

if not exist %3 goto end
md %~n3
move %3 %~n3\P%~n3_V1_A0V0_T07-54-369-664_S00001_Volume.pdf 

if not exist %4 goto end
md %~n4 
move %4 %~n4\P%~n4_V1_A0V0_T07-54-369-664_S00001_Volume.pdf 

if not exist %5 goto end
md %~n5 
move %5 %~n5\P%~n5_V1_A0V0_T07-54-369-664_S00001_Volume.pdf 

if not exist %6 goto end
md %~n6 
move %6 %~n6\P%~n6_V1_A0V0_T07-54-369-664_S00001_Volume.pdf

if not exist %7 goto end
md %~n7 
move %7 %~n7\P%~n7_V1_A0V0_T07-54-369-664_S00001_Volume.pdf

if not exist %8 goto end
md %~n8
move %8 %~n8\P%~n8_V1_A0V0_T07-54-369-664_S00001_Volume.pdf

if not exist %9 goto end
md %~n9 
move %9 %~n9\P%~n9_V1_A0V0_T07-54-369-664_S00001_Volume.pdf



:end

It turns out that the script only modifies up to 9 files at a time. Does anyone know how I can make this change to all files in the folder? Sometimes there are 100,200 or even more pdfs

CodePudding user response:

This should work

# Define variables
$Folder = "C:\myfolder"
$OldFileName = "OldFileName1.pdf"
$NewFileName = "NewFileName1.pdf"

# Get all files in the folder non-recursively
$Files = Get-ChildItem $Folder

# For each file
foreach ($File in $Files){

    # If file matches the OldFileName
    If ($File.Name -eq $OldFileName){

        # Rename the file to the new name
        Rename-Item -Path $File.FullName -NewName $NewFileName

    }

}

CodePudding user response:

Use Get-ChildItem to discover the files, then inspect their BaseName property to get the file name without the extension:

$rootFolder = 'C:\importation'

Get-ChildItem $rootFolder -File -Filter *.pdf |ForEach-Object {
  # create new folder
  $newFolder = mkdir -Path $rootFolder -Name $_.BaseName
  # construct target path
  $targetPath = Join-Path $newFolder.FullName "P$($_.BaseName)_V1_A0V0_T07-54-369-664_S00001_Volume.pdf"
  # move file
  $_ |Move-Item -Destination $targetPath
}
  • Related