PowerShell Random Password Generator


On a project earlier this year, I had to create random passwords for user accounts as part of a provisioning tool.  Perpetually trying to find the fastest way to do something, I came up with a one-liner that you can use to create a random text string from the following ASCII printable characters:

!”#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz{|}~0123456789

To create the passwords, I use this bit of magic:

PS> $Password = ([char[]]([char]33..[char]95) + ([char[]]([char]97..[char]126)) + 0..9 | sort {Get-Random})[0..8] -join ''
PS> $Password
Z-=$fNgb!

Image result for password gif

That will create an 9 character password using the range operator [0..8]. And, if you want to concatenate it with a plaintext counterpart:

PS> $Password = ([char[]]([char]33..[char]95) + ([char[]]([char]97..[char]126)) + 0..9 | sort {Get-Random})[0..8] -join ''
PS> $Password = "Welcome"+$Password
PS> $Password
WelcomeZ-=$fNgb!

Maybe not the most difficult passwords in the world, but probably good enough to give new users the first time they log on to a system.

What ideas do you have?

Comments (4)

  1. turbomcp says:

    Thanks
    very cool

  2. Joe Gasper says:

    First, thank you. Second, do you need the “+ 0..9”? I see numbers in the char[33] to char[95] section. I guess it increases the chance for a number to be included.

    1. Joe–you are right. 0-9 are included in the earlier [char] ranges. I included it again, though, since the problem I found is that if you’re using any password complexity filters, it was occasionally possible to generate a password that only included letters. Once you introduce those extra 10 digits, the probability of you generating a password that the system won’t accept is much lower.

      Maybe there’s a slick way to create a one-liner that pulls “n” number of characters from various character groups to ensure complexity rules are matched?

  3. Nathan says:

    Didn’t work for me.

Skip to main content