Home > Software engineering >  Open All Files in Folder and ReSave in a Created Folder Directory Based on File Name
Open All Files in Folder and ReSave in a Created Folder Directory Based on File Name

Time:09-23

Hello I have over 15K PDF files Saved in a folder Z:\PDF Archive\2010

and need better organization. I have no idea how to do this but what I would like to see happen is: If the file name is 8757854.pdf

I would like to create (if it does not already exist) directory Z:\PDF Archive\8700000-8799999\8750000-8759999\

and Copy the file into it.

Most file names are 7 digits but there are some that are only 6, in that situation, I would like to have a 0 added to the beginning of the file name.

So if the file name is 757854.pdf then this would be the file path: Z:\PDF Archive\0700000-0799999\0750000-0759999\

Thoughts and Ideas would be very appreciated! Thank you in Advance!

CodePudding user response:

Try the following:

# Input and output (root) directory paths.
$inPath = 'Z:\PDF Archive\2010'
$outPathRoot = 'Z:\PDF Archive'

# The max. number of digits in the input file names.
$maxDigits = 7

Get-ChildItem -LiteralPath $inPath -Filter *.pdf | ForEach-Object {

  # Left-pad the number string that constitutes the base file name
  # with zeros to ensure a length of 7.  
  $paddedNum = $_.BaseName.PadLeft($maxDigits, '0')

  # Construct the name of the subdirectories to copy the files to,
  # replacing the digits after the leading 2 and 3 digits first with "0" and "9",
  # respectively, joining the resulting strings with "-"
  $subDirs = 
    foreach ($leadingDigits in $paddedNum.Substring(0, 2), $paddedNum.Substring(0, 3)) {
      ($leadingDigits   '0' * ($maxDigits - $leadingDigits.Length)),
      ($leadingDigits   '9' * ($maxDigits - $leadingDigits.Length)) -join '-'
    }

  # Create the output subdirectories, if necessary.
  # -Force both creates parent directories on demand and 
  # quietly returns an existing directory, if present.
  $targetDir = New-Item -Type Directory -Force ($outPathRoot   '\'   ($subDirs -join '\'))

  # Copy the PDF file at hand to the target subdirectory.
  $_ | Copy-Item -Destination $targetDir.FullName

}

Note: If you add the -WhatIf common parameter to the Copy-Item command, you'll get a preview of the copy operations, which will include the full target path.

  • Related