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

Arrays and Objects

Array.prototype- Allows additional properties of all array objectsArray.from- Creates a new array from an array-like…

PowerShell: Get MD5 Hashing Signature of a File

# Get-MD5-Hash.ps1# Get-FileHash (PowerShell 4.0+) replacement for Windows 2008. Forward-compatible.function getMd5{ param( $file, $md5 =…

WordPress: Gold Price Widget CSS

Here's a sample of CSS Code to customize the display of the WordPress' Gold Pricing…