Home > Software design >  Batch to move files based on total size
Batch to move files based on total size

Time:10-28

I have 900k files in a particular folder that I need to move daily to another folder based on the total size of 100 mbs. I've tried the following code, but it moves 100 files, not the total amount of 100 mbs

@echo on

set Source=C:\Users\%Username%\Desktop\Dropbox\Pre
set Target=C:\Users\%Username%\Desktop\Dropbox\Pos

set MaxLimit=10

for /f "tokens=1* delims=[]" %%G in ('dir /A-D /B "%Source%\*.*" ^| find /v /n ""') do (
move /y "%Source%\%%~nxH" "%Target%"
if %%G==%MaxLimit% exit /b 0
)

pause

I need the batch to move a selection on files that the sum of their size is less than or equal to 10 kbs. Basically to do the same if I manually selected N files that make up 100 mbs. I believe that it didn't work because it checks only the single file size.

CodePudding user response:

The basic problem is that you must keep track of how much data has been copied and check to see if it is over MaxLimit. This is not difficult in PowerShell. This script will copy up to $MaxLimit bytes to $TargetDir. This script requires PowerShell Core 6 . The current stable version at https://github.com/PowerShell/PowerShell is 7.1.5. This can be made to work with the old Windows PowerShell 5.1 by changing the Join-Path statements.

Place these two (2) files in the same directory. When you are confident that the correct files will be copied to the correct directory, remove the -WhatIf from the Move-Item command.

=== Move-PictureBatch.bat

@pwsh -NoLogo -NoProfile -File "%~dp0Move-PictureBatch.ps1"

=== Move-PictureBatch.ps1

#Requires -Version 6
$MaxLimit = 100MB
$SourceDir = Join-Path -Path $Env:USERPROFILE -ChildPath 'Desktop' -AdditionalChildPath 'Pre'
$TargetDir = Join-Path -Path $Env:USERPROFILE -ChildPath 'Desktop' -AdditionalChildPath 'Pos'
$CurrentSize = 0

Get-ChildItem -File -Path $SourceDir |
    ForEach-Object {
        if (($CurrentSize   $_.Length) -lt $MaxLimit) {
            Move-Item -Path $_.FullName -Destination $TargetDir -WhatIf
            $CurrentSize  = $_.Length
        } else {
            break
        }
    }
  • Related