Link to home
Create AccountLog in
Avatar of Sam OZ
Sam OZFlag for Australia

asked on

Script to club and copy files to sub folders

I have  a folder  ( folder is C:\MyFolder  ) where about 150k+ files are kept .  

The files are named sequentially. Sample entries are

RelTdr-000001

RelTdr-000002 ....

................

RelTdr-150000

  

I am looking a  powershell script ( or macro or any means)  by which I can get  folders created  under a root folder (C:\MyFolder\MyRoot)  with 1000 files each ( please keep the count of file  as a variable ) 

The folder can be named sequentially like Fold1, Fold2 , Fold3 ......


Avatar of Qlemo
Qlemo
Flag of Germany image

The files should get moved or copied?

Do you want to run the script again later?

If the last folder won't receive the given count of files, should it be skipped or done?

Avatar of Sam OZ

ASKER

Files should be copied

Run the script now

With last folder , copy should be done 

$root       = 'C:\MyFolder'
$filemask   = 'RelTdr-*'
$foldermask = 'Folder{0:d3}'   # static name plus 3 digits
$batchsize   = 1000

push-location $root

[int] $i  = 0
[int] $fi = 1
Get-ChildItem $filemask -File |
  Sort-Object Name | 
  % {
    if (0 -eq ($i++ % $batchsize))
    {
      # new folder
      $curFolder = $foldermask -f $fi++
      MkDir $curFolder
    }
    Copy-Item $_ $curFolder
  }

pop-location

Open in new window

The script (intentionally) displays the folders created ("Folder001" aso.) as kind of progress indicator.

The parts you can change should be obvious.

The numbers used in file names are irrelevant, the script is just counting the content matching the filemask variable.

The script cannot be run multiple times without receiving errors. If you need to rerun the script for tests, delete the created folders first.

Avatar of Sam OZ

ASKER

Thanks. It works . But can I get a slight modification

Can the Copy happen to a folder C:\CopyFolder   ( PLease keep this a variable ) 

ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer