Home > Enterprise >  Move n files from dump to a destination folder
Move n files from dump to a destination folder

Time:09-27

I want to move n random files from m files in a folder to subfolders. so the final output needs to be some x folders each containing n files. the folder name can be random.

Please help to find a way.

I tried the below PowerShell script and it is creating only empty folders

$filesperfolder = 5000
$sourcePath = "D:\source"
$destPath = "E:\Dest"
$i = 0;
$folderNum = 1;


Get-ChildItem "$sourcePath\*.jpg" | % {

    New-Item -Path ($destPath   "\"   $folderNum) -Type Directory -Force
    Move-Item $_ ($destPath   "\"   $folderNum);

    $i  ;

    if ($i -eq $filesperfolder){
        $folderNum  ;
        $i = 0 ;
    }
}

CodePudding user response:

I would use a while-loop for this like below:

$filesperfolder = 5000     # or should that be: Get-Random -Maximum 5000 -Minimum 1
$sourcePath     = 'D:\source'
$destPath       = 'E:\Dest'
$fileIndex = $folderNum = 0

# append -Filter '*.jpg' if you only want to move .jpg files
$sourceFiles = @(Get-ChildItem -Path $sourcePath -File)
$totalCount  = $sourceFiles.Count
# now loop over the files while $totalCount is greater than 0
while ($totalCount -gt 0) {
    $moveCount = [math]::Min($totalCount, $filesperfolder)  # how many are left?
    $folderNum  
    # create the destination folder if it does not already exist
    $targetFolder = Join-Path -Path $destPath -ChildPath $folderNum
    $null = New-Item -Path $targetFolder -ItemType Directory -Force
    # loop over the number of files to move using the index of the $sourceFiles array
    for ($i = 0; $i -lt $moveCount; $i  ) {
        $sourceFiles[$i   $fileIndex] | Move-Item -Destination $targetFolder
    }
    $totalCount -= $moveCount  # subtract the number of files already moved
    $fileIndex   = $moveCount  # increase the index for the next iteration
}
  • Related