Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest Way to Create a File With Random Data

Tags:

powershell

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 .

like image 780
Dhiwakar Ravikumar Avatar asked Apr 14 '18 20:04

Dhiwakar Ravikumar


People also ask

What is random data 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.

What tool allows the creation of a new file of an arbitrary size?

The best way to create random dump files is by using 'fsutil' in your command prompt.


1 Answers

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)
like image 134
Lieven Keersmaekers Avatar answered Oct 22 '22 08:10

Lieven Keersmaekers