Skip to content
David Kittell
David Kittell

Application & System: Development / Integration / Orchestration

  • Services
    • Application Development
    • Online Application Integration
  • Code
  • Online Tools
  • Tech Support
David Kittell

Application & System: Development / Integration / Orchestration

PowerShell – Random Password Generator

Posted on March 25, 2016January 31, 2017 By David Kittell

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.

Related

Code PowerShell Generate Random PasswordgeneratorpasswordrandomRandom Password Generator

Post navigation

Previous post
Next post

Related Posts

UNIX Bash – Get Latest File Name Based On DateTime

Posted on July 7, 2016

Working on a backup and restore script I often need only to know what the latest backup/archive file is, this command helps you learn that. ls -ltr | tail -1 |cut -d’ ‘ -f10 All information on this site is shared with the intention to help. Before any source code…

Read More

Oracle Clean Date Format

Posted on September 18, 2013October 26, 2015

Sometimes you have to pull a date from Oracle in a cleaner format, this is one way to achieve the format you want. // Convert the Oracle date 19000101 to 01-01-1900 public string OracleCleanDate(string strDate) { if (strDate.Length == 8) { string strYear, strMonth, strDay; strYear = strDate.Substring(0, 4); strMonth…

Read More

UNIX – SED Remove Comment Lines

Posted on January 23, 2017

This script will remove all lines that start with # along with all comments. Whatever file you choose I suggest you view first then execute sed "/^\s*#/d;s/\s*#[^\"’]*$//" /etc/dnsmasq.conf && sed ‘/^\s*$/d’ /etc/dnsmasq.conf sudo sed -i "/^\s*#/d;s/\s*#[^\"’]*$//" /etc/dnsmasq.conf && sudo sed -i ‘/^\s*$/d’ /etc/dnsmasq.conf All information on this site is shared…

Read More

Code

Top Posts & Pages

  • PowerShell - Rename Pictures to Image Taken
  • PowerShell - IIS Remove Site
  • Front Page
  • SQLite - Auto-Increment / Auto Generate GUID
  • PowerShell - FTP Upload Directory With Sub-Directories

Recent Posts

  • Javascript – Digital Clock with Style
  • BASH – Web Ping Log
  • BASH – Picture / Video File Name Manipulation
  • Mac OSX Terminal – Create SSH Key
  • Bash – Rename Picture

Top Posts

  • PowerShell - Rename Pictures to Image Taken
  • PowerShell - IIS Remove Site
  • SQLite - Auto-Increment / Auto Generate GUID
  • PowerShell - FTP Upload Directory With Sub-Directories
  • Raspberry Pi - Remove Default Apps
  • PowerShell - Change Windows CD/DVD Drive Letter
©2025 David Kittell | WordPress Theme by SuperbThemes