Generating Random Passwords

Here is a very simple way to create complex random passwords:

Add-Type -AssemblyName System.Web
$PasswordLength = 12
$SpecialCharCount = 3
[System.Web.Security.Membership]::GeneratePassword($PasswordLength, $SpecialCharCount)

The API call lets you choose the length of the password, and the number of non-alphanumeric characters it contains.

Twitter This Tip! ReTweet this Tip!

  • Very handy... is there a way to exclude characters?

  • I set the special character count to 1, and I get 5.

    regilicha:

    Function GeneratePswd {

    param(

    $Length,

    $CharSet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

    )

    $CSLen = $CharSet.Length - 1

    $Pswd = ''

    for (; $Length -gt 0; --$Length) {

    $Pswd += $CharSet.Substring((random $CSLen),1)

    }

    return $Pswd

    }

    Set your own charset, or pass the function what you want.

    For something like this function, you could pass the special characters and count as well, create two strings, then insert the special characters into the other password randomly.

  • or even shorter:

    Add-Type -AssemblyName System.Web;[System.Web.Security.Membership]::GeneratePassword(15,4)

    As for excluding chars. use regex replace to drop chars you don't want.

  • or from an earlier example on this site...

    -join ('abcdefghkmnrstuvwxyzABCDEFGHKLMNPRSTUVWXYZ23456789$%&*#'.ToCharArray() | Get-Random -Count 8)