PowerShell: Generate Random Password

Previous version that does not require System.Web assembly:

PowerShell RandomPassword Function

# This function will quickly generate a random password string with certain complexities to save your brain for more daydreaming

function generateRandomPassword{
    param(
        $minLength = 10,
        $maxLength = 16,
        $nonAlphaChars = 2,
        $excludeRegex='[:\$\%\&\,]',
        $replaceExclusionWith=@(',',';','!','/','{','^','+','-','*','_')
    )
    add-type -AssemblyName System.Web
    $randomLength = Get-Random -Minimum $minLength -Maximum $maxLength    
    $randomPassword = [System.Web.Security.Membership]::GeneratePassword($randomLength, $nonAlphaChars)
    $sanitizedPassword = $randomPassword -replace $excludeRegex,"$(Get-Random -InputObject $replaceExclusionWith)"
    $fixedRepeating = .{$rebuiltString=''
                        for ($i=0;$i -lt $sanitizedPassword.length;$i++){
                        $previousChar=$sanitizedPassword[$i-1]
                        $thisChar=$sanitizedPassword[$i]
                        $nextChar=$sanitizedPassword[$i+1]
                        if($thisChar -eq $nextChar){
                            do{
                                $regenChar=[char](Get-Random (65..122) )
                                }until($regenChar -ne $previousChar -and $regenChar -ne $nextChar)
                            $rebuiltString+=$regenChar
                            }
                        else{$rebuiltString+=$thisChar}
                        }
                        return $rebuiltString
                        }
                            
    return $fixedRepeating 
}
generateRandomPassword
# Troubleshooting:
# add-type -AssemblyName System.Web
# Preempts this error:
#Unable to find type [System.Web.Security.Membership].
#At line:1 char:1
#+ [System.Web.Security.Membership]::GeneratePassword(24,5)
#+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#+ CategoryInfo          : InvalidOperation: (System.Web.Security.Membership:TypeName) [], RuntimeException
#+ FullyQualifiedErrorId : TypeNotFound

Leave a Reply

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