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

Check a List of Servers to Find Currently Stopped Autorun Services

$username = (Get-ADDomain).name+'\USERNAME' $Password = 'PASSWORD' $pass = ConvertTo-SecureString -AsPlainText $Password -Force $cred = New-Object…

PowerShell: Remove Hyper-V VM Snapshots

Hyper-V's snapshot feature is a double-edged sword. It's a convenient method to make a quick…

PowerShell: Set PasswordNeverExpires on SamAccountName

Quick 1-liner Code $accounts=@( 'orange', 'apple', 'pear', 'dog', 'cat', 'dinosaur', 'chicken', 'cow', 'yomama', 'yodada' )…
Other project: DragonCoin.com