Lazy Random Password Generation in PowerShell
So, good passwords are pretty fashionable these days - with an eye towards the ever-relevant XKCD.
Sometimes you just want a short method to generate a random string, with some control over which characters are used.
Here's a method I use when I need to do this with no external requirements:
-join( 33..126 | Get-Random -Count 16 | %{ [char]$_ } )
NB: I'm embarrassed to say I took a variant of this from somewhere a while ago (maybe someone showing something in Slack), and can't remember where from. If anyone recognises this, please let me know and I'll attribute.
Pretty simple (if you ignore the short-form)!
This breaks down to an array of numbers (33..126
), which is piped to Get-Random
to select a given amount (-Count 16
), each of which (or ForEach-Object
of which, I guess) is then cast to a [char]
. This entire set of chars is then wrapped in a -join()
, converting it to a single string with no separator character.
You can, of course, be much more specific with which characters you want to allow by specifying a combination of the following number-ranges:
Value(s) | Characters |
33..47 | !"#$%'()*+,-./ |
48..57 | 0-9 |
58..64 | :;<=>?@ |
65..90 | A-Z |
91..96 | [\]^_` |
97..122 | a-z |
126 | ~ |
So, for mixed-case alphanumeric you could use 48..57 + 65..90 + 97..122
We can quickly and easily display the value-to-character mapping by running something like this:
33..126 | %{[PSCustomObject]@{Number = $_; Value = [char]$_}} | Out-GridView
Examples:
# Create PSCredential
$Credential = [PSCredential]::New(
"TestUser",
(-join( 48..57 + 65..90 + 97..122 | Get-Random -Count 16 | %{ [char]$_ } ) | ConvertTo-SecureString -AsPlainText -Force)
)