FileCreator/New-RandomFileScript.psm1

#region New-RandomFileScript
Function New-RandomFileScript
{
<#
    .SYNOPSIS
    Create a new file with random contents.
 
    .DESCRIPTION
    The New-RandomFile cmdlet creates files with random contect and specific size.
 
    .PARAMETER File
    The path to the file.
 
    .PARAMETER MegaByte
    The size of the file in Megabytes
 
    .PARAMETER ShowProgress
    Show the progress of the operation
 
    .EXAMPLE
    New-RandomFile -File testfile.txt -Megabyte 10
    This command will create a new file named testfile.txt with 10MB size.
#>


    param
    (
        [Parameter(Mandatory = $true, Position = 0)]
        [String]$Path,

        [Parameter(Mandatory = $false, Position = 1)]
        [ValidateRange(1, 5120)]
        [UInt16]$MegaByte = 1,

        [Switch]$ShowProgress
    )

    # get/create the file's full path
    $p = if (Test-Path $Path -PathType Leaf)
    {
        Resolve-Path $Path
    }
    else
    {
        Join-Path $pwd $File
    }

    $total = 1mb * $MegaByte
    $strings = $bytes = 0

    # create the stream writer
    $sw = New-Object IO.streamWriter $p

    # get a 64 element Char[]; I added the - and _ to have 64 chars
    [char[]]$chars =
    'azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN0123456789-_'

    1..$MegaByte | ForEach-Object {
    # get 1MB of chars from 4 256KB strings
        1..4 | ForEach-Object {
            # randomize all chars and...
            $rndChars = $chars | Get-Random -Count $chars.Count

            # ...join them in a string
            $str = -join $rndChars

            # repeat random string 4096 times to get a 256KB string
            $str_ = $str * 4kb

            # write 256KB string to file
            $sw.Write($str_)

            # show progress
            if ($ShowProgress)
            {
                $strings++
                $bytes += $str_.Length
                Write-Progress -Activity "Writing String #$strings" `
                               -Status "$bytes Bytes written" `
                               -PercentComplete ($bytes / $total * 100)
            }

            # release resources by clearing string variables
            Clear-Variable str, str_
        }
    }

    $sw.Close()
    $sw.Dispose()
    # release resources through garbage collection
    [GC]::Collect()
}
#endregion

#region Exports
Export-ModuleMember -Function New-RandomFileScript
#endregion