function Create-RandomPassword ( [int] $minLength = 8, [int] $maxLength = 8, [bool] $useSymbols = $false, [bool] $asSecureString = $false ) { [System.Security.Cryptography.RNGCryptoServiceProvider] $random = new-object System.Security.Cryptography.RNGCryptoServiceProvider # Get an array of all characters that can be used in the password [string] $choice = Get-CharacterChoice -useSymbols $useSymbols $randomPassword = $null if (($minLength -le $maxLength) -and ($minLength -ge 6)) { # Allocate a byte array of dimension 1 $randomNumber = new-object byte[] 1 if ($minLength -eq $maxLength) { [int] $length = $minLength } else { # Calculate a random length between minLength and maxLength $random.GetBytes($randomNumber) [int] $length = $minLength + $randomNumber[0] % ($maxLength - $minLength + 1) } # Allocate a byte array of dimension $length $randomSequence = new-object byte[] $length $hasUCase = $hasLCase = $hasNum = $false while(!$hasUCase -or !$hasLCase -or !$hasNum) { # Generate random sequence of bytes $random.GetBytes($randomSequence) # Ensure that there is at least one number, uppercase # character and lowercase character in the sequence. $hasUCase = $hasLCase = $hasNum = $false foreach($b in $randomSequence) { [char]$char = $choice[$b % $choice.Length] if ($char -ge 'A' -and $char -le 'Z') { $hasUCase = $true } if ($char -ge 'a' -and $char -le 'z') { $hasLCase = $true } if ($char -ge '0' -and $char -le '9') { $hasNum = $true } } } if ($asSecureString) { $randomPassword = new-object System.Security.SecureString } else { [string] $randomPassword = '' } # Assign the password from the sequence of random bytes foreach($b in $randomSequence) { [char]$char = $choice[$b % $choice.Length] if ($asSecureString) { $randomPassword.AppendChar($char) } else { $randomPassword += $char } } } return $randomPassword } # Outputs an array of all the characters that the generated password # can be made up of. function Get-CharacterChoice ( [bool] $useSymbols = $true ) { if ($useSymbols) { [string] $choice = '!"#$%&''()*+,-./' } else { [string] $choice = '' } $choice += '23456789' if ($useSymbols) { $choice += ':;<=>?@' } $choice += 'ABCDEFGHJKMNPQRSTUVWXYZ' if ($useSymbols) { $choice += '[\]^_`' } $choice += 'abcdefghjkmnpqrstuvwxyz' if ($useSymbols) { $choice += '{|}~' } return $choice }