Wednesday, March 18, 2009

Random Password Generator

Here I'm using a VERY simple function to generate a random password. The function is mainly built around the use of the new V2 CTP cmdlet called Get-Random. This cmdlet takes all the headache out of using the code like this:

$r = New-Object system.Random
$r.next(1,100)

I know, it's not a lot of typing but with the Get-Random cmdlet really is much easier to generate random numbers, plus it has the ability of choosing random items from any given array from the pipeline.

This code is VERY simple compared to some of those password scripts out there.

function Get-RandomPassword {
param([int]$length = 4)
@(1..$length | % { [char](Get-Random -Minimum 48 -Maximum 122) }) -join ''
}

Here, I'm simply grabbing a set number of random ascii characters and using the new join operator to join the characters to spit out the random password.

All that is needed now is to add this to your profile or to a module; import and your ready to start pumping passwords through. Pretty easy eh!

I will post later with the Advanced Function version of this so it can be used in the pipeline and with built-in help features.

No comments: