Often you may want to use PowerShell to generate a random password with a specific length.
There are two common ways to do so:
Method 1: Generate Random Password with Special Characters
Add-Type -AssemblyName 'System.Web'
[System.Web.Security.Membership]::GeneratePassword(12, 4)
This particular example uses the GeneratePassword method to generate a random password that is 12 total characters in which at least 4 of them are special characters.
Method 2: Generate Random Password without Special Characters
[System.Web.Security.Membership]::GeneratePassword(12, 4)
This particular example creates a password that is 12 total characters and only includes letters and numbers.
The following examples show how to use each method in practice.
Example 1: Generate Random Password with Special Characters in PowerShell
Arguably the easiest way to generate a random password in PowerShell is to use the GeneratePassword() method after loading the System.Web assembly.
For example, you can use the following syntax to generate a random password with 12 total characters in which at least 4 of the characters are special characters:
Add-Type -AssemblyName 'System.Web'
[System.Web.Security.Membership]::GeneratePassword(12, 4)
The following screenshot shows how to use this syntax in practice:

We ran this code 4 times and received a different 12-character random password each time.
Note that each password contains at least 4 special characters, although some of the passwords contain even more special characters.
For example, the last password generated contains a total of 6 special characters:
- Lh#N*g*4r.^]
The nice part about using the GeneratePassword() method is that it has the potential to include all of the following types of characters in the password:
- lowercase letters
- uppercase letters
- numbers
- special characters
Example 2: Generate Random Password without Special Characters in PowerShell
If you would like to generate a random password in PowerShell and not include special characters, then you can use the following syntax:
-join((0x30..0x39)+( 0x41..0x5A)+( 0x61..0x7A) | Get-Random -Count 12 | % {[char]$_})
Note that the number after the -Count operator specifies the length of the password.
The following screenshot shows how to use this syntax in practice:

We ran this code 4 times and received a different 12-character random password each time.
Note that each password contains only letters and numbers. None of the random passwords contain special characters.
Note: This method works by generating a random string of uppercase letters, lowercase letters, and numbers, then using the Get-Random cmdlet to choose a random subset of a specific number of characters.
Related Tutorials
The following tutorials explain how to perform other common tasks in PowerShell:
PowerShell: How to Use Get-ChildItem with Filter
PowerShell: How to Use Get-ChildItem to Get Full Path of Files
PowerShell: How to List Files in Directory by Date
