Generating a random password with PowerShell

Instead of bashing on the keyboard, I’m a proponent of using a tool to generate a random password, such as when creating a service account or new user accounts.  A colleague of mine recently discovered that this is doable with Windows PowerShell, in only two lines!

Add-Type -Assembly System.Web
[Web.Security.Membership]::GeneratePassword($length,$numberOfNonAlphanumericCharacters)

This will return a string using the provided parameters.  For example, setting $length = 15 and $numberOfNonAlphanumericCharacters = 6 the output is

uC@#H=}S&K$C!RP

or

1P*]v)PL99T{$y;

or

%H2|kK5J{D=(-kl

(You get the idea.)

MSDN provides more detail on the GeneratePassword method. Sadly it only allows up to 128 characters in length.

Disclaimer: The information on this site is provided "AS IS" with no warranties, confers no rights, and is not supported by the authors or Microsoft Corporation. Use of included script samples are subject to the terms specified in the Terms of Use .

Comments

  • Anonymous
    January 08, 2013
    nice

  • Anonymous
    February 21, 2014
    The second parameter is the MINIMUM number of non-alphanumeric characters; you may end up with more.

    This probably doesn't matter but does explain why I was confused until I read the MSDN link properly :-)

  • Anonymous
    May 01, 2014
    Thank you works great

  • Anonymous
    October 06, 2014
    This blog post is part of a series of posts on Security Best Practices for Microsoft Azure Applications