If you want to move the files instead of copying them, simply replace Copy-Item with Move-Item. The Move-Item command will transfer each file to the target group folder, removing it from the original location.

Here's the updated script:

$sourceFolder = "C:\path\to\your\folder"
$destinationFolder = "C:\path\to\output\folder"
$filesPerGroup = 1000

# Get all files from the source folder, including subfolders
$allFiles = Get-ChildItem -Path $sourceFolder -File -Recurse

# Check if there are enough files to process
if ($allFiles.Count -eq 0) {
    Write-Output "No files found in the specified folder or its subfolders."
} else {
    # Shuffle the files list by selecting random files
    $allFiles = $allFiles | Sort-Object {Get-Random}

    # Calculate the number of groups
    $groups = [math]::ceiling($allFiles.Count / $filesPerGroup)
    Write-Output "Total groups to create: $groups"

    for ($i = 0; $i -lt $groups; $i++) {
        # Create a new folder for each group
        $groupFolder = "$destinationFolder\Group_$($i + 1)"
        New-Item -ItemType Directory -Path $groupFolder -Force | Out-Null

        # Get the files for this group by using array slicing
        $startIndex = $i * $filesPerGroup
        $endIndex = [math]::Min(($startIndex + $filesPerGroup), $allFiles.Count)
        $groupFiles = $allFiles[$startIndex..($endIndex - 1)]

        Write-Output "Processing Group $($i + 1) with $($groupFiles.Count) files."

        # Move files to the group folder
        $groupFiles | ForEach-Object { 
            Move-Item $_.FullName -Destination $groupFolder 
        }

        Write-Output "Group $($i + 1) completed and saved to $groupFolder"
    }
    Write-Output "All groups have been processed successfully."
}

Explanation of the Changes

  • Move-Item: Replaces Copy-Item with Move-Item, transferring each file to the destination folder and removing it from the original location.

This version will move files instead of copying them, organizing them into the specified groups without keeping duplicates in the original folder.