Create large file with random data with Powershell

$path      = "C:\Temp\random20GB.bin"
$sizeBytes = [long]20GB
$chunkSize = [int]64MB

$buffer = New-Object byte[] $chunkSize
$rng    = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$fs     = [System.IO.File]::Open($path, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write)

try {
    $written = [long]0
    while ($written -lt $sizeBytes) {
        $toWrite = [int][Math]::Min([long]$chunkSize, $sizeBytes - $written)
        $rng.GetBytes($buffer)
        $fs.Write($buffer, 0, $toWrite)
        $written += $toWrite
        Write-Progress -Activity "Generating file" `
            -Status ("{0:N1} / {1:N1} GB" -f ($written/1GB), ($sizeBytes/1GB)) `
            -PercentComplete (($written / $sizeBytes) * 100)
    }
}
finally {
    $fs.Close()
    $rng.Dispose()
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.