FileCreator/New-RandomFileScript.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#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