Generate a Random Password in PowerShell

This builds three random 20-character passwords from a set of letters, numbers and symbols:

PowerShell
$chars = [char[]]'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#$%*-_'
1..3 | ForEach-Object { -join (1..20 | ForEach-Object { $chars | Get-Random }) }

Each password is on its own line. Change the 20 for a different length and the 3 for a different count.

Windows PowerShell 5.1: a $chars array without look-alike characters, then three random 20-character passwords built with ForEach-Object and Get-Random

Leave Out the Look-Alikes

The character set has no 0, O, 1, l or I. Those are easy to misread when a password is read out or typed from a screen. Add or remove symbols to suit whatever the password is for, since some systems reject certain ones.

Get-Random Is Not Cryptographically Secure

Microsoft’s documentation for Get-Random says it does not ensure cryptographically secure randomness. For a test account that is fine. For a real account, PowerShell 7.4 and later can use the .NET secure generator, which picks from the same set in one call:

PowerShell
[System.Security.Cryptography.RandomNumberGenerator]::GetString($chars, 20)

That method does not exist in Windows PowerShell 5.1, where the line fails with does not contain a method named 'GetString'. Run it from PowerShell 7 instead. Install PowerShell 7 on Windows shows how to have both side by side.

Copy It Straight to the Clipboard

PowerShell
[System.Security.Cryptography.RandomNumberGenerator]::GetString($chars, 20) | Set-Clipboard

The password goes to the clipboard without being printed, so it does not sit in the console where someone can see it.

Related

If SQL Server is part of your day job, my current work lives over at sqldba.blog: production DBA scripts, an error library and the SSMS guide.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *