I have a requirement to create files of a specified size filled with random data. I can't use any third party tools to achieve this so all I have at my disposal is all the Powershell commands.
What I have here works well with small files ranging in size from 1 KB to a 30 KB. It doesn't scale well when the file becomes large.
function makeFile([String]$filename, [int]$SizeInKb) {
$str = ""
$size = 29 * $SizeInKb
if (-not (Test-Path $filename)) {
New-Item $filename -ItemType File | Out-Null
for ($i=1; $i -le $size; $i++) {
# A GUID is 36 characters long
# We will create a string 29*36 (1044) characters in length and
# multiply it with $SizeInKb
$str += [guid]::NewGuid()
}
write $str to a file barring the last ($SizeInKb * 20) + 2 characters.
$strip_length = ($SizeInKb * 20) + 2
("$str").Remove(0, $strip_length) | Out-File "$filename" -Encoding ascii
}
}
Is there a better way to create files with random data? I'm currently generating GUIDs and then writing them to a file .
A random file is made up of a series of records of identical length. A record can correspond to a scalar data type, such as Integer or String, or to a user-defined type, in which each record is broken down into fields corresponding to the members of the type.
The best way to create random dump files is by using 'fsutil' in your command prompt.
Following writes a set of random bytes to a file and is still pretty fast
Edit
Kudos to Tom Blodget for pointing out an issue in decoding/encoding
$bytes = 10MB
[System.Security.Cryptography.RNGCryptoServiceProvider] $rng = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
$rndbytes = New-Object byte[] $bytes
$rng.GetBytes($rndbytes)
[System.IO.File]::WriteAllBytes("$($env:TEMP)\test.txt", $rndbytes)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With