Generate random password for AD using PowerShell

When we create new bulk of AD users from CSV or from any other system, first, we need to create strong random password to provide password for every new AD user. In Powershell, we don’t have any built-in cmdlet to generate a random AD password string. However we can use the cmdlet Get-Random to select random number or random character from the given character array.

The following powershell command creates a 12 -character new password. But the password generated by this method may not accepted by Active Directory in some cases.

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

The problem with the above method is that we can not guarantee that the new password will be accepted by Active Directory that has strong password policy since it could return a password containing only lowercase letters a-z or only uppercase letters A-Z. To overcome this problem, we need to write a custom function to generate a strong random password that will be complex enough for Active Directory.

The function to create strong password is already written by Simon Wahlin. You can directly 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).

——- EXAMPLE 1 ——-

C:PS> New-SWRandomPassword
DUo&S7XJh
    
Will generate one password with a length between 8  and 12 chars.

——- EXAMPLE 2 ——-

 C:PS> New-SWRandomPassword -MinPasswordLength 8 -MaxPasswordLength 14
7d&5cnaB

Will generate a password with a length between 8  and 14 chars.

——- EXAMPLE 3 ——-

C:PS> New-SWRandomPassword -InputStrings abc, ABC, 123 -PasswordLength 4
3ABa
    
Generates a password with a length of 4 containing atleast one char from each InputString

Advertisement

Leave a Comment