PowerShell Script
The following function generates a random complex password string.
By default it will return a 16 character pattern featuring:
- At least 1 lower case letter
- At least 1 upper case letter
- At least one number; and
- 6 non-alpha characters.
It’s length and number of non-alphanumeric characters are parameterised and may be supplied if desired.
function New-ComplexPassword {
[CmdletBinding()]
[OutputType([String])]
param
(
[Parameter(
Mandatory = $false,
ValueFromPipelineByPropertyName = $true,
Position = 0)]
[ValidateNotNull()]
[Int]
$PasswordLength = 16,
# A validation is done here otherwise it may never meet the criteria for upper, lower, number etc
[Parameter(
Mandatory = $false,
ValueFromPipelineByPropertyName = $true,
Position = 1)]
[ValidateScript( { $_ -lt $PasswordLength - 2 })]
[Int]
$NumNonAlphaChars = 6
)
process {
# Using the .NET supplied method with customisations.
Add-Type -AssemblyName 'System.Web'
$validPassword = $false
do {
$generatedPassword = [System.Web.Security.Membership]::GeneratePassword($PasswordLength, $NumNonAlphaChars)
If ($generatedPassword -cmatch "(?=.*\d)(?=.*[a-z])(?=.*[A-Z])") {
$validPassword = $True
}
} While ($validPassword -eq $false)
$generatedPassword
}
}
PowerShell Sample Output
New-ComplexPassword
U]+1M?05+bf]Q)ZD
New-ComplexPassword -PasswordLength 8 -NumNonAlphaChars 2
Z75{If>7