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 .