Secure Password Generation In PowerShell

Nice simple one today. Very short and easy. Just made a big post to my job automation project which is why I made the following script in PowerShell. Basically what I needed was to be able to reset multiple user account passwords in Active Directory. This meant that I needed to generate secure passwords, this was to ensure that they would meet the minimum requirements, and also convert them to something that PowerShell and Active Directory “liked”.

The below 3 lines of code should do the trick:

[string]$initialpassword = ([char[]](Get-Random -input $(47..57 + 65..90 +97..122) -count 8)) + (Get-Random -minimum 0 -maximum 10)

$passwordwithspacesremoved = $initialpassword.Replace(' ','')

$convertedpassword = ConvertTo-SecureString -AsPlainText $passwordwithspacesremoved -Force

I had the add the extra “Get-Random -Minimum 0 -Maximum 10” because, since its randomly generated, sometimes it didn’t include a single number. This obviously would make the password not secure enough to be used within Active Directory. So rather than waste time trying to define the randomness to include some sort of number, I simply made damn sure that there would always be a random digit at the end. Both ensuring sufficient security to be used in Active Directory and also still being random. (Wouldn’t be good if all the passwords ended in 3 :p )

How I used this code, only if you’re interested though is like this:

Set-ADAccountPassword -Identity $USERNAME$ -Reset - NewPassword $convertedpassword -PassThru | Enables-ADAccount | Unlock-ADAccount

As you can see, I have passed the secure string password into the account reset command. Works like a charm. Some of the other parameters (such as -PassThru) stops the process being weird /breaking.


Leave a Reply