Thursday, August 26, 2010

random passwords in powershell


recently i was teaching my students how to read hundreds of user accounts from a text file and create them in active directory in seconds with a powershell script. to the script we added a nifty function to generate random initial passwords that meet the complexity requirements of windows. here's our function:

9 # new_password
10 # Returns a string.
11 # Generates a random password for the user that meets Windows' complexity
12 # requirements.
13 function new_password {
14 $randomizer = New-Object System.Random
15 $password = [char] $randomizer.next(65,91) # Uppercase letters
16 $password += [char] $randomizer.next(48,58) # Numbers
17 $password += [char] $randomizer.next(91,127) # Lowercase letters
18 # and punctuation
19 foreach ($time in 1..7) {
20 $password += [char] $randomizer.next(32,127)
21 }
22 return $password
23 } # end function new_password
24

don't forget to write the passwords out to a file when you're done so that you can tell users what they are:

.
.
.
62 # Write the username and password to a file.
63 "{0,-19} {1}" -f $samAccountName, $password >> userspass.txt
64 "-" * 30 >> userspass.txt
65

until next time.

No comments:

Post a Comment