Posted On July 10, 2020

PowerShell: Generate Random Password

kimconnect 0 comments
blog.KimConnect.com >> Codes >> 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 *

Related Post

How To Invoke Functions as Background Jobs

Invoke-Command, Start-Job, Multi-Tasking is what good coders should aspire toward. Here, we're looking at some…

PowerShell: Copy Active Directory User

# copyADUser.ps1 # Version 0.01 $fromUsername='mTyson' $newUserFirstname='Bruce' $newUserLastname='Lee' $newPassword='SOMEPASSWORD' $newEmailAddress='[email protected]' $setProxyAddress=$false function copyADUser{ param( $fromUsername,…

How to Remove Question Mark ‘Info’ Button in SyntaxHighlighter

If you're looking for a way to remove this subtle, yet spammy link: Do this:Goto…