Powershell random password generator – with complexity!

Recently we needed to automate password randomization for account creation purposes. In order to ensure the password policy was met we needed, 8 characters total, 1 uppercase letter, 1 number, and 1 special character. We also needed to control the character set of special characters due to certain finicky applications. This script grabs a base password from http://random.org, verifies that it has all but our special character, and finally randomly inserts one of our special characters into the password.

Function Get-Seed{
# Generate a seed for future randomization
$RandomBytes = New-Object -TypeName 'System.Byte[]' 4
$Random = New-Object -TypeName 'System.Security.Cryptography.RNGCryptoServiceProvider'
$Random.GetBytes($RandomBytes)
[BitConverter]::ToInt32($RandomBytes, 0)
}

do
{
$initialPW = $(Invoke-RestMethod https://www.random.org/passwords/?num=1&len=7&format=plain&rnd=new) -replace "`n"

if($initialPW -cmatch "[A-Z]") { $containsUpper = $True } else { $containsUpper = $False }
if($initialPW -cmatch "[a-z]") { $containsLower = $True } else { $containsLower = $False }
if($initialPW -match "[0-9]") { $containsNumbr = $True } else { $containsNumbr = $False }

$specCharArray = [Char[]]"!#$&*_-"
$specChar = $($specCharArray | Get-Random -Count 1)

if (($containsUpper -eq $True) -and ($containsLower -eq $True) -and $($containsNumbr -eq $True))
{
$seed = $(Get-Random -Maximum 7 -Minimum 1 -SetSeed $(Get-Seed))
$initialPW.Insert($seed,$specChar)
break
}
}
While ($True)

Leave a Reply

Your email address will not be published. Required fields are marked *