Powershell: Random String Generator | Zak Emerick's IT Blog

My IT blog for random ideas and solutions.

Powershell: Random String Generator

The script below will generate a random string using the character set and length that you specify. Right now the character sets are pretty limited, but can be easily adjusted. I plan on adding the ability to pass a character set to the function from the pipeline. Right now though, it is sufficient. It’s also pretty efficient. I generated a 100,000 character string using alpha-num-special keyspace in 52 seconds on average hardware.

It’s strange that Powershell doesn’t have something like this already built-in. PS 5 (not sure about previous versions.) has a Get-Random cmdlet that you can generate large random numbers, but not strings. (Correct me if I’m wrong)

Anyway— This will serve its purpose. Please leave comments intact if you plan on using this function.

function Get-RandomString {
<#
.SYNOPSIS
Generates a random string of specified length from the given character set.
 
.DESCRIPTION
The function will take the length and character set, generate a random string, 
and put that string into the pipeline.
 
.PARAMETER Length 
The length of the string that you want put into the pipeline. This parameter has a default value of ten.
 
 
.PARAMETER CharSet
The character set that you want the random string generated from. The valid strings are alpha, alphanum, num, and all.
This parameter has a default value of alpha (upper and lowercase letters)
 
 
.EXAMPLE
Generate a random string of 20 characters with alpha-numeric character set.
Get-RandomString -Length 20 -CharSet alphanum
 
.EXAMPLE 
Run the function with no parameters is like running Get-RandomString -Length 10 -CharSet alpha
Get-RandomString
 
.NOTES
This function is capable of generating VERY large strings. I've generated upwards of 1,000,000 characters.
 
.AUTHOR
Zak Emerick
zemerick@emerickcc.com
http://www.emerickcc.com
#>
[CmdletBinding()]
param(
    [int]$Length = 10,
    [ValidateSet('alpha','alphanum','num','all')]
    [string]$CharSet = 'alpha'
)
    begin {
    [string]$out = ''
 
    # Build valid character array
        switch ($CharSet) {
            'alpha' { 
                65..90 + 97..122 | ForEach-Object { $Dict += [char]$_ } 
            }
            'alphanum' { 
                65..90 + 97..122 + 48..57 | ForEach-Object { $Dict += [char]$_ } 
            }
            'num' {
                48..57 | ForEach-Object { $Dict += [char]$_ }
            }
            'all' { 33..122 | Foreach-Object { $Dict +=[char]$_ } }
        }
    }
    process {
        while ($length -ge 1) {
            [int]$i = Get-Random -Maximum $Dict.Length
            $out += $Dict[$i]
            $length--
        }
    }
    end {
        Write-Output $out
    }
}
673 Total Views 1 Views Today


Post a Comment

Your email address will not be published. Required fields are marked *

 characters available