DEV Community

Cover image for Password generation in PowerShell Core (6+)
Yann Normand
Yann Normand

Posted on • Updated on

Password generation in PowerShell Core (6+)

In PowerShell (as in Windows PowerShell), the commonly referenced way to generate a user password is to call the Membership.GeneratePassword method from the System.Web assembly.

Add-Type -AssemblyName System.Web
# Generate random password
[System.Web.Security.Membership]::GeneratePassword(8,2)
Enter fullscreen mode Exit fullscreen mode

This is all well and good but System.Web is not part of .NET Core that Powershell Core (6+) depends on.

Fret not.

While there is no built-in password generation method out of the box, it doesn't take much to write our own.

The key to generating a strong random password is to use a cryptographic random number generator.

Don't roll your own crypto

Meet Get-Random.

In the absence of -SetSeed parameter, Get-Random takes its seed from the cryptographic RandomNumberGenerator, which makes it suitable for our scenario.

Let’s generate a password that meets the following requirements, to satisfy common password restrictions:

  • At least 12 characters long
  • Requires 3 out of 4 of the following:
    • Lowercase characters.
    • Uppercase characters.
    • Numbers (0-9).
    • Symbols (!@#$%^&*).
$symbols = '!@#$%^&*'.ToCharArray()
$characterList = 'a'..'z' + 'A'..'Z' + '0'..'9' + $symbols

function GeneratePassword {
    param(
        [ValidateRange(12, 256)]
        [int] 
        $length = 14
    )

    do {
        $password = -join (0..$length | % { $characterList | Get-Random })
        [int]$hasLowerChar = $password -cmatch '[a-z]'
        [int]$hasUpperChar = $password -cmatch '[A-Z]'
        [int]$hasDigit = $password -match '[0-9]'
        [int]$hasSymbol = $password.IndexOfAny($symbols) -ne -1

    }
    until (($hasLowerChar + $hasUpperChar + $hasDigit + $hasSymbol) -ge 3)

    $password | ConvertTo-SecureString -AsPlainText
}
Enter fullscreen mode Exit fullscreen mode

The logic is to randomly select characters from the allowed list
for a given length, and to keep trying until the password meets the restrictions.

If this script is too slow for your needs,here is a slightly altered faster version (~0.4ms instead of 10ms on a Mac Book Pro 2015).

Discussion (1)

Collapse
ericcsinger profile image
Eric C. Singer

Just wanted to say thanks for putting this together. I learned a few tricks I didn't know before in addition to solving the need for a random PWD generator.