How to generate random password using PowerShell

When we creating new bulk of users in any system, we need to create random password to provide unique password for every user. In Powershell, there is no cmdlet to create a random password string. However we can use many custom methods to generate random string.

# Method 1: (Using System.Random object)

We can use the .NET class object System.Random to extract values in the range of 33-126 that are the characters from the ASCII table. The following powershell code creates a 10 -character new password:

$randomObj = New-Object System.Random
$newPassword=""
1..10 | ForEach { $newPassword = $newPassword + [char]$randomObj.next(33,126) }
Write-Host $newPassword -ForegroundColor 'Yellow'

# Method 2: (Get-Random cmdlet)

We can also use the cmdlet Get-Random to select random number or random character from the given collection. The following powershell command creates a 10 -character new password. We need to pipe a bunch of chars to Get-Random to get a random character.

$chars = "abcdefghijkmnopqrstuvwxyzABCEFGHJKLMNPQRSTUVWXYZ23456789!#%&?".ToCharArray()
$newPassword=""
1..10 | ForEach {  $newPassword += $chars | Get-Random }
Write-Host $newPassword -ForegroundColor 'Yellow'

# Method 3: (With AD Password Policy)

The problem with above two methods is that we can not guarantee that the password will be accepted by system with strong password policy (i.e. Active Directory). AD system with complex password policy may not accept the above random password since it could return a password containing only lowercase letters a-z. To overcome this problem, we need to write a custom function to generate a random passwords that will be complex enough for Active Directory.

Now, I am not going write any function since this work already nicely done by Simon Wahlin. You can download the script from technet gallery:
https://gallery.technet.microsoft.com/Generate-a-random-and-5c879ed5

The function can be run in two ways, either using the parameter –PasswordLength to set a fixed password length or using the parameters –MinPasswordLength and –MaxPasswordLength to use a random length.

Both ways takes the parameters –Count and –InputStrings. -Count specifies how many passwords to generate and -InputStrings specifies a list of strings defining which chars to use for password generation. Each generated password will contain atleast one char from each string (as long as PasswordLength => number of strings).


Advertisement

Leave a Comment