0

I'm trying to write a script, that will select N number of files randomly, and move them to folders named 1, 2, 3.. Then it must compress each folder, and run another batch/script.

The script I use to randomly copy N number of files, is:

gci somefolder | random -c $x | mi -dest someotherfolder

Example of what I need:

C:\somefolder (has 11000 files)
C:\1 (has 2000 files)
C:\2 (has 2000 files)
C:\3 (has 2000 files)
C:\4 (has 2000 files)
C:\5 (has 2000 files)
C:\6 (has 1000 files)

Then each folder is compressed to

C:\1.zip
C:\2.zip
C:\3.zip
C:\4.zip
C:\5.zip
C:\6.zip

And lastly, it will run a simple another batch file (Thinking of FTP'ing files)

0

1 Answer 1

2

A big thank you to //\O// for his out-zip function! This will do what you want:

function out-zip { 
    Param([string]$path) 

    if (-not $path.EndsWith('.zip')) {$path += '.zip'} 

    if (-not (test-path $path)) { 
      set-content $path ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) 
    } 
    $ZipFile = (new-object -com shell.application).NameSpace($path) 
    $input | foreach {$zipfile.CopyHere($_.fullname)} 
}
$Path = "C:\Temp"
$FileList = gci $path
[int]$FilesPerZip=100
For($i=1;$i -le [Math]::Ceiling($FileList.count/$FilesPerZip);$i++){
    md "c:\$($i)"
    gci $path|random -Count $FilesPerZip|%{$_.moveto("c:\$i\$($_.name)")}
}
(1..[Math]::Ceiling($FileList.count/$FilesPerZip))|%{gi "c:\$_"|out-zip "C:\$_.zip"}

Just update your path and how many files you want in each zip file.

This counts how many files in total, divides by how many files you want per zip file, and rounds up. Then it loops through the target directory grabbing X files at random and placing them into sequential numbered folders. Lastly it zips those folders.

It will fail if there are already zip files with the desired name existing already (i.e. C:\1.zip), and will probably throw errors if there are those folders there as well, and will fail if there are those folders AND there are matching files in them, so you will probably want to throw in some checks up front to make sure those folders and files don't exist already, but this answers your Move & Zip question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.