Skip to content

Instantly share code, notes, and snippets.

@figueroadavid
Created November 7, 2019 16:40
Show Gist options
  • Select an option

  • Save figueroadavid/f5c25c1efe6708b2ec412b519eff9e52 to your computer and use it in GitHub Desktop.

Select an option

Save figueroadavid/f5c25c1efe6708b2ec412b519eff9e52 to your computer and use it in GitHub Desktop.
Generates new temporary passwords, and optionally validates they are AD compliant for complexity
Function New-TempPassword {
param(
[parameter(ValueFromPipelineByPropertyName, ValueFromPipeline)]
[ValidateScript({ $_ -ge 8 })]
[int32]$PasswordLength = 20,
[parameter(ValueFromPipelineByPropertyName)]
[int32]$MinimumNonAlphaNumericCharacters = 1,
[parameter(ValueFromPipelineByPropertyName)]
[switch]$ActiveDirectory,
[parameter(ValueFromPipelineByPropertyName)]
[switch]$ReturnSecure
)
if ($MinimumNonAlphaNumericCharacters -gt $PasswordLength) {
throw 'The $MininumNonAlphaCharacters cannot exceed the size of $PasswordLength'
}
Add-Type -AssemblyName System.Web -ErrorAction SilentlyContinue
$NewPassword = [System.Web.Security.Membership]::GeneratePassword($PasswordLength, $MinimumNonAlphaNumericCharacters)
if ($ActiveDirectory) {
$NumberOfMatchingSets = 0
if ($NewPassword -cmatch '[a-z]') { $NumberOfMatchingSets ++ }
if ($NewPassword -cmatch '[A-Z]') { $NumberOfMatchingSets ++ }
if ($NewPassword -cmatch '[-!@#$%^&*()_+=[{\]};:<>|./?]') { $NumberOfMatchingSets ++ }
if ($NewPassword -match '\d') { $NumberOfMatchingSets ++ }
if ($NumberOfMatchingSets -ge 3) {
Write-Verbose -Message 'Password meets ActiveDirectory complexity requirements'
}
else {
Write-Verbose -Message 'Password does not meet ActiveDirectory complexity requirements; trying again'
New-TempPassword @PSBoundParameters
}
}
if ($ReturnSecure) {
$NewPassword | ConvertTo-SecureString -AsPlainText -Force
}
else {
$NewPassword
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment