Create random passwords in Powershell

Published: 2011-10-21

RandomPassword function can be used to create random passwords in PowerShell based environments. It accepts a password length and an optional pattern (full or partial). A random pattern will be created or added if not specified. You can use patterns to make sure that your passwords has a guaranteed password complexity.

Examples:

# 8-char password with a random pattern
RandomPassword -length 8

12-char with a partial start pattern “ULNS”:

one uppercase, one lowercase, one numeric, one specific

the last six pattern classes will be generated in random

RandomPassword -length 12 -pattern “ULNS”

10-char with a full pattern “LLLLSUUUUN”:

four lowercase, one special, four uppercase and one numeric

RandomPassword -length 10 -pattern “LLLLSUUUUN”

Show code
#####
# RandomPassword: Create a random password
# with a specified length and optional pattern

function RandomPassword { param ( $length, $pattern # optional )

# Define classes of character pools, there are four classes
# by default: L - lowercase, U - uppercase, N - numeric,
# S - special
$pattern_class = @("L", "U", "N", "S")

# Character pools for classes defined above
$charpool = @{ 
    "L" = "abcdefghijklmnopqrstuvwxyz";
    "U" = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    "N" = "1234567890";
    "S" = "!#%&"
}

$rnd = New-Object System.Random

# Introduce a random delay to avoid same random seed
# during frequent calls
Start-Sleep -milliseconds $rnd.Next(500) 

# Create a random pattern if pattern is not defined or
# fill the remaining if the pattern length is less than
# password length
if (!$pattern -or $pattern.length -lt $length) {

    if (!$pattern) {
        $pattern = ""
        $start = 0
    } else {
        $start = $pattern.length - 1
    }

    # Create a random pattern
    for ($i=$start; $i -lt $length; $i++) {
        $pattern += $pattern_class
    }

    # DEBUG: write-host "Random pattern : $pattern" 
 }

 $password = ""

 for ($i=0; $i -lt $length; $i++) {   
    $wpool = $charpool$pattern]      
    $password += $wpool    
 }                

 return $password

}