2010-03-09

Generate a Random Password - Powershell

A task that I do quite often when building a new System is to create random password a local user on the machine – Don’t ask – it is a an OPSEC requirement from way before my time.

So instead of Running my fingers of the keyboard in a random way and having my colleagues ask what I am doing each time I decided to simplify this Powershell.

Dmitry Sotnikov’s post set me in the correct direction, the result below is a function that will prompt you for the length you want, create a password and put it in your clipboard

#========================================================================
# 
# NAME: Generate-password
# 
# AUTHOR: Maish Saidel-Keesing
# DATE  : 09/03/2009
# 
# COMMENT: Will generate a random password according to required length
#
# ========================================================================

function Generate-Password () {
    param ()
    PROCESS {
         if ($args.count -eq 0)  {
                do {
                $length = Read-Host "How many characters long should the password be?"
                } until ($length -ne $null)
            } else { $length = $args[0] }

    #load Assembly
    [Reflection.Assembly]::LoadWithPartialName("System.Web")
    $password = [System.Web.Security.Membership]::GeneratePassword($length,3) 
    $password | clip
    Write-host The password is now in your clipboard
    }
}


Line 16-20. If there is no argument passed then it will prompt you for the number of characters needed in the password

Line 23. load the System.Web.Security Namespace

Line 24. Generate the password. The two parameters that are needed are password length and numberOfNonAlphanumericCharacters

Line 25. clip is a command line utility for the clipboard. In this case I piped it into the clipboard so I could paste it into the password window.