#PSTip Quickly generate a password

Note: This tip requires PowerShell 2.0 and above

Generating a password usually consists of creating separate collections containing uppercase letters, lowercase letters, numbers and non-alphanumeric characters (@,%,$,^,&,*, etc…) and then randomizing the collections and pulling a specific number from each collection and then randomizing those into a password.

A more simple approach is to use the System.Web assembly that can be loaded using Add-Type.

PS> Add-Type -AssemblyName System.Web

Once loaded, you can make use of the GeneratePassword() from the System.Web.Security.Membership class. This method requires 2 parameters in order to properly create a password string to use. The first parameter is an integer to determine the length of the password which can be between 1 and 128 characters. The second parameter that is required is also an integer to determine the number of non-alphanumeric characters that will be used in the password. This number cannot be greater than the first parameter for the password length, otherwise the operation will fail.

PS> [System.Web.Security.Membership]::GeneratePassword(15,4)

Pretty handy to use if you are provisioning a lot of accounts and need to assign a password for each account. Being that this is something that can be quite useful; I wrapped this up into a simple function called New-Password that can be used to generate a password.

PS> New-Password -PasswordLength 18 -NumNonAlphaNumeric 9

Function New-Password {


    Param (
        [Int]$PasswordLength = 15,
        [Int]$NumNonAlphaNumeric = 7

    If ($NumNonAlphaNumeric -gt $PasswordLength) {
        Write-Warning ("NumNonAlphaNumeric ({0}) cannot be greater than the PasswordLength ({1})!" -f`

    Add-Type -AssemblyName System.Web

About the author: Boe Prox

Boe Prox is a Microsoft MVP in PowerShell and currently a System Administrator who has been in the IT field since 2003 and supporting a variety of different platforms. You can find him at his blog http://learn-powershell.net as well as on twitter @proxb or working on one of his codeplex projects: PoshWSUS, PoshPAIG, PoshChat and PoshEventUI.

Related Posts