<# .SYNOPSIS Create folders with randomized content .DESCRIPTION This script generates n random folders each limited to a size y in MB which are then filled randomly with files included in the filter .NOTES Author: Jan-Hendrik Peters / www.janhendrikpeters.de Date: 2015-05-14 .PARAMETER SourcePath The source path of the files to be copied .PARAMETER NumberOfFolders The number of folders to be created .PARAMETER MaxFolderSizeInMB The maximum folder size in Megabyte .PARAMETER OutputPath The target parent path within which the folders should be created .PARAMETER FileFilter The file filter as required by the Get-ChildItem cmdlet .PARAMETER WhatIf Use to test the copy action before #> param ( [Parameter(Mandatory=$true)] [ValidateScript({Test-Path $_ -PathType 'Container'})] [string]$SourcePath = "Z:\Musik", [Parameter(Mandatory=$true)] [int]$NumberOfFolders = 6, [Parameter(Mandatory=$true)] [int]$MaxFolderSizeInMB = 650, [Parameter(Mandatory=$true)] [string]$OutputPath = "D:\GT_Music", [Parameter(Mandatory=$true)] [string]$FileFilter = "*.mp3", [switch]$WhatIf ) [hashtable]$Files = @{} [hashtable]$UsedRandoms = @{} $Count = 0 Get-ChildItem -Path $SourcePath -Filter $FileFilter -Recurse | foreach{ $Files.Add($Count, $_) $Count ++ } if($Files.Count -eq 0) { Write-Warning "No suitable files ($FileFilter) found in $SourcePath! Hint: Include wildcards (*) in your filter." exit 1 } function Get-SuperRandom { param ($Minimum,$Maximum) $Maximum = $Maximum + 1 $IsRandom = $false if($UsedRandoms.Count -ge $Maximum) { throw "Out of random numbers" } while(!$IsRandom) { $Random = Get-Random -Minimum $Minimum -Maximum $Maximum if($UsedRandoms.ContainsKey($Random)) { $IsRandom = $false } else { $IsRandom = $true $UsedRandoms.Add($Random, $true) Write-Output $Random } } } if(!(Test-Path $OutputPath)) { try { $null = New-Item -ItemType Directory -Path $OutputPath -WhatIf:$WhatIf -ErrorAction Stop } catch { Write-Warning "Error creating output path $OutputPath. Exiting." exit 2 } } foreach($CD in 1..$NumberOfFolders) { $TargetPath = Join-Path $OutputPath $CD if(!(Test-Path $TargetPath)) { try { $null = New-Item -ItemType Directory -Path $TargetPath -WhatIf:$WhatIf -ErrorAction Stop } catch { Write-Warning "Error creating output path $TargetPath. Exiting." exit 2 } } $TotalSize = 0 while($TotalSize -le $MaxFolderSizeInMB) { try { $Rnd = Get-SuperRandom -Minimum 0 -Maximum $Files.Count } catch { $TotalSize = $MaxFolderSizeInMB + 12345 continue } Write-Progress -Activity "Filling up CD $CD" -Status "Copying $($Files[$Rnd].Name)" -Id 666 -PercentComplete ($TotalSize/$MaxFolderSizeInMB*100) Copy-Item -Path ($Files[$Rnd].FullName) -Destination $TargetPath -ErrorAction SilentlyContinue -WhatIf:$WhatIf $TotalSize = $TotalSize + ([math]::Round($Files[$Rnd].Length / 1024 /1024)) } }