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:


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

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

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 (5)

  1. turbomcp says:

    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.

    1. What version of PowerShell are you using?

      I tested in both Windows Server 2012 and 2008 R2:

      PS C:\> $PSVersionTable

      Name Value
      —- —–
      CLRVersion 2.0.50727.5485
      BuildVersion 6.1.7601.17514
      PSVersion 2.0
      WSManStackVersion 2.0
      PSCompatibleVersions {1.0, 2.0}
      PSRemotingProtocolVersion 2.1

      PS C:\> $Password = ([char[]]([char]33..[char]95) + ([char[]]([char]97..[char]126)) + 0..9 | sort {Get-Random})[0..8] -j
      oin ”
      PS C:\> $Password
      PS C:\>
      PS C:\> $PSVersionTable

      Name Value
      —- —–
      PSVersion 4.0
      WSManStackVersion 3.0
      CLRVersion 4.0.30319.34209
      BuildVersion 6.3.9600.17400
      PSCompatibleVersions {1.0, 2.0, 3.0, 4.0}
      PSRemotingProtocolVersion 2.2

      PS C:\> $Password = ([char[]]([char]33..[char]95) + ([char[]]([char]97..[char]126)) + 0..9 | sort {Get-Random})[0..8] -join ”
      PS C:\> $Password
      PS C:\>

Skip to main content