PowerAddict.net

powerAddict.NET

by Lou Goban
IT Application Professional at Syntax

How to generate strong password in PowerShell

Updated version on 13.July 2021

# GENERATE PASSWORD
Function GetRandomChars($length, $characters) {
    $random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
    $private:ofs=""
    return [String]$characters[$random]
}

Function ScrambleString([string]$inputString){     
    $characterArray = $inputString.ToCharArray()   
    $scrambledStringArray = $characterArray | Get-Random -Count $characterArray.Length     
    $outputString = -join $scrambledStringArray
    return $outputString 
}

Function GenPassword {
    Write-Host "`r`n[INFO] Generating password.." -ForegroundColor Yellow
    $password = GetRandomChars -length 7 -characters 'abcdefghiklmnoprstuvwxyz'
    $password += GetRandomChars -length 4 -characters 'ABCDEFGHKLMNOPRSTUVWXYZ'
    $password += GetRandomChars -length 3 -characters '1234567890'
    $password += GetRandomChars -length 2 -characters '!$%&=?@#+'

    $script:pass = ScrambleString $password
    $script:secpass = ConvertTo-SecureString $pass -AsPlainText -Force

    Write-Host $pass
    Write-Host "[OK] Password generated.." -ForegroundColor Green
}
# GENERATE PASSWORD END

Leave the first comment