The PoSH Student

October 12, 2010

Generate-Password

Filed under: PowerShell — Tags: , , , , , , , — Nathan @ 8:12 pm

I generate random passwords a lot. Anytime I need a service account, or when creating new user accounts, I need a random password to use. But I don’t want it to be too random, lest I confuse 1, l, and I because of some font variant somewhere. The natural result: a function!

function Generate-Password {
	Param (
		[int]$Length = 8,
		[string]$Chars = "ABCDEFGHJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789",
		[switch]$Help
		)

	If ($Help) {
		Write-Host -f yellow @"
PURPOSE:
  Generate random password of a specific type
USAGE:
  Generate-Password [[-Length] <int>] [-Chars <string>]
  Defaults to 8 characters long. Specify [-Length] characters if needed.
  Defaults to all upper & lowercase letters and numbers, except confusable ones like
    0,O,1,l, etc. Specify your own [-Chars] as needed.
EXAMPLE:
  Generate-Password 25 "§©ª«À¿¾æñ¶¤¨«®±µð÷"
  Make a 25 character password of untypeable characters.
"@
		break
		}

	$random = New-Object random
	$result = ""
	for ($i=0; $i -lt $length; $i++) {
		$result += $chars[$random.Next(0,$chars.Length)]
		}
	
$result
	}

It’s actually a very simple thing, but I use it almost daily, and sometimes for unexpected things. Need a large string to play with for testing? Generate a 1024 character password, or 128 eight-character ones. Want a huge password of untypeable characters? Here’s one for every character from [CHAR]0 to [CHAR]255 that prints using the Consolas font:

Generate-Password -Length 50 -Chars [string]::Join("", (((33..126)+(161..255)) | %{[char]$_}))

I keep this in a Functions.ps1 file that can be called by all my scripts, so it is available any time I need randomized characters.

Advertisement

1 Comment »

  1. [...] generate a very long string of random characters to use. I use my Generate-Password function to make a 48 character password of every printable character (with the Consolas font, anyway) in [...]

    Pingback by How to hide a password in a script « The PoSH Student — October 12, 2010 @ 9:14 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.