Generating random data into a file is important task that can be accomplished in PowerShell. Generating random data is useful for benchmarking reading and writing files. We will also do it fast! We can generate 1GB of random data into a file in about 800 ms.

⚠️ Do not use System.Security.Cryptography.RNGCryptoServiceProvider as it is obsolete, instead use System.Security.Cryptography.RandomNumberGenerator. System.Security.Cryptography.RandomNumberGenerator is good as we don’t have to create a new object and can use the static methods.

# Amount of random bytes
$bytes = 10KB

# Create RNG
[System.Security.Cryptography.RandomNumberGenerator] $rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()

# Create Byte array of size $bytes
$randomBytes = New-Object byte[] $bytes

# Make the random bytes
$rng.GetBytes($randomBytes)

# For WriteAllBytes seems like full path is needed, other it outputs to user home directory (~)
$filePath = "C:\temp\random-data.txt"

# Write random bytes to file
[System.IO.File]::WriteAllBytes($filePath, $randomBytes)