0

Simple Random Password Generator Using Powershell

If you’ve been searching for a simple random password generator using Powershell, this script is going to be your one stop shop for exactly what you’re looking for. I’m sure many of you have heard the password phrase “correct horse battery staple”, we’ll today I’m going to share the script to display a password phrase exactly like that. After scouring the internet, I was able to compile a list of over 8,000 commonly used English words that we can use to generate our passwords.
 

The default word list is compiled using a combination of three to nine letter words and I’ve added the ability to set how many words from the word list to use. There are actually a couple of parameters that were built in to the script to give you the flexibility to comply with Active Directory complexity requirements, or something pretty simple. It’s entirely up to you how complex you want it.

Correct Horse Battery Staple Explained

The idea of correct horse battery staple comes from the xkdc comic where you had a pretty decent password but because of the character replacements and combinations, it was hard to remember. In their example, the password “Tr0ub4dor&3” was used and their argument was that it was easier for programs to crack as well as difficult for humans to type in and remember, thus making it a little less secure because it’s more prone to be written down.
 

However, with a password like ‘correct horse battery staple’ the argument is just the opposite. It’s relatively easy for humans to remember but difficult for computers to crack because of the length of the password itself. I’m sure programs these days are probably accounting for this technique which is why I’ve added a bit more flexibility than just all lowercase words. Spaces, special characters and numbers assist with the complexity and it still makes it relatively easy for humans to remember. If you want a bit more detail and can use a bit of entertainment, Dr. Mike Pound from the Computerphile Youtube Channel is hilariously fantastic at doing just that.
 

Personally, I use a Password Manager and all my passwords are random combinations of upper, lower, numbers and special characters. Most are 25+ characters that are generated by using my Powershell Random Password Generator script and saved into my vault. So, if you prefer something like that, check out that link.

Script Parameters

    WordCount

Specify the number of words you would like to grab from the wordlist. e.g -WordCount 4

    RemoveSpaces

By default, every word (except the last word) has a space so it’s easier on the eyes and adds length to the password. This switch will remove spaces.

    RemoveNumbersAndSpecialCharacters

Similar to the RemoveSpaces switch, this will generate a password without numbers and special characters.

    WordListFilePath

If you think our word list is complete weak sauce, you can specify your own .TXT file and use words of your choosing (1 word per line). If your list is not found or is not a txt file, it will revert to the online word list. e.g C:\WordList.txt

Simple Random Password Generator Using Powershell

Let’s now share our correct horse battery staple generator. As I mentioned it is pretty flexible so it can comply with Active Directory and Azure Active Directory password complexity requirements, yet still be simple enough to remember.
 

Function New-SimpleRandomPassword {
<#
.SYNOPSIS
    This will generate a simple random password like "correct horse battery staple" and include numbers and/or special characters after each word

.NOTES
    Name: New-SimpleRandomPassword
    Author: theSysadminChannel
    Version: 1.0
    DateCreated: 2021-Aug-26

.LINK
    https://thesysadminchannel.com/simple-random-password-generator-using-powershell -

.EXAMPLE
    For updated examples, use Help New-SimpleRandomPassword -Online
#>

    [CmdletBinding(
        SupportsShouldProcess,
        ConfirmImpact = 'Medium'
    )]
    param(
        [Parameter(
            Mandatory = $false
        )]
        [ValidateRange(2,20)]
        [int]   $WordCount = 3,


        [Parameter(
            Mandatory = $false
        )]
        [switch]  $RemoveSpaces,


        [Parameter(
            Mandatory = $false
        )]
        [switch]  $RemoveNumbersAndSpecialCharacters,


        [Parameter(
            Mandatory = $false
        )]
        [string]  $WordListFilePath

    )


    BEGIN {
        $SpecialCharacters = @((33,35) + (36..38) + (40..46) + (60..62) + (64))
        $Numbers = @(48..57)
    }

    PROCESS {
        try {
            if ($PSBoundParameters.ContainsKey('WordListFilePath')) {
                if ((Test-Path $WordListFilePath) -and 
                    ((Get-Item $WordListFilePath | select -ExpandProperty Extension) -eq '.txt')) {
                   
                        $FullList = Get-Content $WordListFilePath
                } 
            }

            #If the local wordlist was not found or the file was not a txt file, grab a wordlist online
            if (-not $FullList) {
                $Site = Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/theSysadminChannel/Wordlists/master/WordList'
                $FullList = $Site.Content.Trim().split("`n")
            }
                
            [System.Collections.ArrayList]$3LtrWord = @()
            [System.Collections.ArrayList]$4LtrWord = @()
            [System.Collections.ArrayList]$5LtrWord = @()
            [System.Collections.ArrayList]$6LtrWord = @()
            [System.Collections.ArrayList]$7LtrWord = @()
            [System.Collections.ArrayList]$8LtrWord = @()
            [System.Collections.ArrayList]$9LtrWord = @()

            #Separating words into different arrays.
            foreach ($Word in $FullList) {
                switch ($word.Length) {
                    3 {$3LtrWord.Add($Word) | Out-Null}
                    4 {$4LtrWord.Add($Word) | Out-Null}
                    5 {$5LtrWord.Add($Word) | Out-Null}
                    6 {$6LtrWord.Add($Word) | Out-Null}
                    7 {$7LtrWord.Add($Word) | Out-Null}
                    8 {$8LtrWord.Add($Word) | Out-Null}
                    9 {$9LtrWord.Add($Word) | Out-Null}
                }
            }

            #Minimum 14 character password if we remove spaces and special characters
            if ($WordCount -le 3) {
                $WordList = $7LtrWord + $8LtrWord + $9LtrWord
            }

            if ($WordCount -eq 4) {
                $WordList = $4LtrWord + $5LtrWord + $6LtrWord + $7LtrWord
            }

            if ($WordCount -eq 5) {
                $WordList = $4LtrWord + $5LtrWord + $6LtrWord
            }
            
            if ($WordCount -ge 6) {
                $WordList = $3LtrWord + $4LtrWord + $5LtrWord
            }

            $Password = 1..$WordCount | ForEach-Object {
                if ($_ -eq $WordCount -or $PSBoundParameters.ContainsKey('RemoveNumbersAndSpecialCharacters')) {
                    $WordList | Get-Random -Count 1
                } else {
                    ($WordList | Get-Random -Count 1) + 
                    ([char]($SpecialCharacters + $Numbers | Get-Random -Count 1))
                }
            }

            if ($PSBoundParameters.ContainsKey('RemoveSpaces')) {
                ($Password -as [string]).Replace(' ','')
            } else {
                $Password -as [string]
            }

        } catch {
            Write-Error $_.Exception.Message
        }
    }

    END {}

}

 

Simple Random Password Generator Using Powershell Example

How To Run Simple Random Password Generator Script

In the recent versions of Powershell (5.0+), it has become much easier to load a function into memory. No more are the days where we need to dot source a function to load it. It can still be done but many people seem to get confused when I try to explain it so we’ll cover 3 methods and you can choose what works best for you.
 

  • Copy and Paste the entire function into Powershell
  • Import the .ps1 as a Module
  • Dot Source the function into memory

 

Copy and Paste the entire function into Powershell

Yup! You read that right. Copy the code and Ctrl+V right into Powershell. Once its copied, it’s now loaded into memory so all you will need to do is run New-SimpleRandomPassword with the parameters you’re looking for and voila. It’s done!

 

Import the .ps1 as a Module

Similar to how you Import Modules like ActiveDirectory, AzureAD etc.. you can also import a single .ps1 to be able to run it.
Import-Module C:\_Scripts\New-SimpleRandomPassword.ps1

 

Dot Source the function into memory

Back to the basics and how I initially learned how to load functions into Powershell. This is actually dependent on where you save the .ps1, but let’s say you saved it into the C:\_Scripts folder. I’ll typically load it by putting a “.” and the path to the script. Example.. (notice the ‘dot’ before the file path)

. C:\_Scripts\New-SimpleRandomPassword.ps1

 
Any of the 3 ways above should get you going and allowing you to start generating your simple passowrds.

Conclusion

So hopefully this was able to help you out and provide some examples for seeing a full Powershell script but also its function Simple Random Password Generator Using Powershell. If you like Powershell scripts like this and have a use for more real world scripts, be sure to check out our own Powershell Gallery. I wrote all of the scripts there and they’re completely free for you to use to make your sysadmin life hopefully easier through automation.

5/5 - (6 votes)

Paul

Hi, my name is Paul and I am a Sysadmin who enjoys working on various technologies from Microsoft, VMWare, Cisco and many others. Join me as I document my trials and tribulations of the daily grind of System Administration.