Generating Passwords with PowerShell

Password reuse is not a good practice. If there’s any doubt, there are great discussions about this on security.stackexchange.com. So while being vigilant to have unique passwords for each account/service, the following PowerShell scripts have been quite useful.

Specific or Limited Character Set

Some accounts/services require a specific set of characters. For those instances, the following PowerShell script is used since the variable $pwdCharSet will contain the allowed character set. While 1..15 signifies for the password to be 15 characters long. The script is just a loop that grabs a random character from $pwdCharSet fifteen times.

NOTE: this method of password generation doesn’t require importing any additional modules or .NET components (as shown below).

$pwdCharSet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'.ToCharArray()
$(1..15 | %{ $pwdCharSet | Get-Random }) -join ''

To condense this into a one-liner:

$(1..15 | %{ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890'.ToCharArray() | Get-Random }) -join ''

Alternative – Specific or Limited Character Set

The Microsoft Scripting Guys blog post Generate Random Letters with PowerShell provides an alternative method of the prior technique by casting each random number as a [char].

For a refresher, the following one-liner will display each number and the [char] casting result.

33..126 | %{ "`t{0}`t{1}" -f $_,[char]$_ }

Once you have the correct character range dialed in, the one-liner provided by the Scripting Guys will produce the same results without having to type out the entire character set.

The following will create a 15 character password using 0-9A-Za-z.

-join ((48..57) + (65..90) + (97..122) | Get-Random -Count 15 | % {[char]$_})

.NET – System.Web.Security

This method has been discussed on a Microsoft TechNet Blog – How to Generate a Secure Random Password using PowerShell. It leverages the System.Web.Security namespace in System.Web.dll. When a web application manages it’s own accounts, this is often used for secure password generation.

For PowerShell to use it, the assembly must first be loaded.

Add-Type -AssemblyName System.Web

From Microsoft documentation, the Membership.GeneratePassword(Int32, Int32) method has two parameters:

  1. length [Int32] – The number of characters in the generated password. The length must be between 1 and 128 characters.
  2. numberOfNonAlphanumericCharacters [Int32] – The minimum number of non-alphanumeric characters (such as @, #, !, %, &, and so on) in the generated password.

Invoking this static method can be achieved via the following.

[System.Web.Security.Membership]::GeneratePassword(15,5)

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.