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

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






(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 (4)
  1. Frédéric Lambillotte says:


  2. Doug says:

    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 🙂

  3. Gene says:

    Thank you works great

  4. Anonymous says:

    This blog post is part of a series of posts on Security Best Practices for Microsoft Azure Applications

Comments are closed.

Skip to main content