Copy files until they exceed a specified size

1.9k views Asked by At

I need to copy files to a folder until they exceed a specified size. I've written the following script but it fails with the following error:

Cannot compare "Microsoft.PowerShell.Commands.GenericMeasureInfo" because it is not IComparable. At C:\33.ps1:8 char:1 + "{0:N2}" -f ($colItems.sum / 1024MB)

$files = Get-ChildItem C:\source -Recurse | % { $_.FullName }

foreach($file in $files) {
    do {

        Copy-Item $file -Recurse D:\target
        $colItems = (Get-ChildItem d:\target -recurse | `
                         Measure-Object -property length -sum)
        "{0:N2}" -f ($colItems.sum / 1024MB)
    }
    while ($colItems -le 10)
}

What am I doing wrong?

1

There are 1 answers

0
Martin Brandl On BEST ANSWER

The while condition will be verified after the first do loop. Since you already enumerate through the files, your script will copy all files.

You can omit the do-while loop and break the foreach if the limit is reached:

$files=Get-ChildItem C:\source -Recurse | % { $_.FullName }
$sum = 0
$sizeLimitInGB = 10

foreach($file in $files) 
{
    $colItems = (Get-ChildItem d:\target -recurse | Measure-Object -property length -sum)

    if (($colItems.sum / 1GB) -gt $sizeLimitInGB)
    {
        break; # Limit reached.
    }

    Copy-Item $file -Recurse D:\target
}