PowerShell – Random Password Generator

|

Similar to C# – Random Password Generator but this will work with PowerShell scripts.

This script has a minimum of four (4) characters but you can change that to whatever you would like.

.\RandomPasswordGenerator.ps1 <Password Length>
<#
    .SYNOPSIS
        New-RandomPassword generates a random password
    .DESCRIPTION
        New-RandomPassword generates a random password that meets the following rules:
            A password:
                - Needs to have at least one of each of these:
                    1. Lower case character
                    2. Upper case character
                    3. Number
                    4. Special character
                - Has a certain length.
                - Needs a random amount of each of the required types in a random order.
    .PARAMETER Length
        Length of the password
    .EXAMPLE
        New-RandomPassword 8
    .INPUTS
        System.Int32
    .OUTPUTS
        System.String
#>
 
clear
 
function New-RandomPassword($PasswordLength)
    {
        # Length of the password to be generated
        #$PasswordLength = 20

        if($PasswordLength -lt 4) {$PasswordLength = 4}
         
        # Used to store an array of characters that can be used for the password
        $CharPool = New-Object System.Collections.ArrayList
 
        # Add characters a-z to the arraylist
        for ($index = 97; $index -le 122; $index++) { [Void]$CharPool.Add([char]$index) }
 
        # Add characters A-Z to the arraylist
        for ($index = 65; $index -le 90; $index++) { [Void]$CharPool.Add([Char]$index) }
 
        # Add digits 0-9 to the arraylist
        $CharPool.AddRange(@("0","1","2","3","4","5","6","7","8","9"))
         
        # Add a range of special characters to the arraylist
        $CharPool.AddRange(@("!","""","#","$","%","&","'","(",")","*","+","-",".","/",":",";","<","=",">","?","@","[","\","]","^","_","{","|","}","~","!"))
         
        $password=""
        $rand=New-Object System.Random
         
        # Generate password by appending a random value from the array list until desired length of password is reached
        1..$PasswordLength | foreach { $password = $password + $CharPool[$rand.Next(0,$CharPool.Count)] }   
         
        #print password
        $password
}
 
$pwdLengthArg = $args[0]
$runscript = 1
 
# Check Parameter Input - Start
if($pwdLengthArg -eq $null) {
    write-host "Error: Password Length is missing"
    $runscript = 0
}
# Check Parameter Input - Stop
 
# If $runscript = 0 show instructions
if (!($runscript -eq 1))
{    
    write-host "`n .\RandomPasswordGenerator.ps1 <Password Length>`n"
}
else
{
    New-RandomPassword $pwdLengthArg
}

Reference: http://www.wisesoft.co.uk/scripts/powershell_random_password_generator.aspx

Another approach

Function Get-RandomPassword {
  Param(
    [parameter()]
    [ValidateRange(8,100)]
    [int]$Length=12,
 
    [parameter()]
    [switch]$SpecialChars
 
  )
    $aUpper      = [char[]]'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    $aLower      = [char[]]'abcdefghijklmnopqrstuvwxyz'
    $aNumber     = [char[]]'1234567890'
    $aSCharacter = [char[]]'!@#$%^&*()_+|~-=\{}[]:;<>,./' # Depending on usage, you may want to strip out some of the special characters if they are not supported
    $aClasses    = [char[]]'ULN' #represents the different classes of characters
    $thePass     = ""
    if ($SpecialChars){
        $aClasses += 'S'
    }
    $notOneOfEach = $true
    while ($notOneOfEach){
        $pPattern = ''
        for ($i=0; $i-lt $Length; $i++){
            $pPattern += get-random -InputObject $aClasses
        }
        if (($pPattern -match 'U' -and $pPattern -match 'L' -and $pPattern -match 'N' -and (-not $specialChars)) -or ($pPattern -match 'U' -and $pPattern -match 'L' -and $pPattern -match 'N' -and $pPattern -match 'S')){
            $notOneOfEach = $false
        }
    }
    foreach ($chr in [char[]]$pPattern){
        switch ($chr){
            U {$thePass += get-random -InputObject $aUpper; break}
            L {$thePass += get-random -InputObject $aLower; break}
            N {$thePass += get-random -InputObject $aNumber; break}
            S {$thePass += get-random -InputObject $aSCharacter; break}
        }
    }
    $thePass
}
 
clear
 
for ($i=0; $i -le 20; $i++){Get-RandomPassword -length 16}

Reference: http://poshcode.org/5806

Originally Posted on March 25, 2016
Last Updated on January 31, 2017
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.