Generate random password with PowerShell

So I was updating the PowerGUI AD pack the other day and wanted to add random password generation function for Reset Password action.

Here’s the code I came up with:

#Set up random number generator
$rand = New-Object System.Random
#Generate a new 10 character password
1..10 | ForEach { $NewPassword = $NewPassword + [char]$rand.next(33,127) }
#Reset the password
Set-QADUser "Dmitry Sotnikov" -UserPassword $NewPassword

That’s it. I guess I could get more fancy by ensuring that characters from 3 out of 4 character groups are present, etc. but this was the easiest one-liner to keep me going.

Tags: , , , , , , , ,

4 Responses to “Generate random password with PowerShell”


  1. 1 Adam Bell July 18, 2007 at 11:23 am

    HI Dimitry,

    I have a function thats not as simple as yours, but does generate complex passwords. It’s filed under the less than obvious post:
    http://www.leadfollowmove.com/archives/powershell/powershell-less-code-same-result

    I was comparing the same function between VBS and PoSH, and used a password gen function as my sample.

    Cheers

    Adam :)

  2. 2 dmitrysotnikov July 18, 2007 at 7:22 pm

    Hey Adam! Thanks for the link. I agree that technically my oneliner might in some cases fail to generate a complex password but I wanted it so much to be a oneliner! ;)

    Anyway, I’m glad you posted a link to your script so folks can find an alternative while reading this post.

    Dmitry

  3. 3 Simpler yet! July 29, 2007 at 5:10 am

    Here’s an even simpler call for password generation

    If you already have the assembly loaded, you can skip the first line:
    [Reflection.Assembly]::LoadWithPartialName(”System.Web”)

    Then it really is a one-liner

    [System.Web.Security.Membership]::GeneratePassword(10,2)

  4. 4 dmitrysotnikov July 29, 2007 at 6:53 am

    Wow! Yes, it looks like you can use the method standalone without other Membership functionality, so yes, great tip! Learning something new every day.


Leave a Reply




View Dmitry Sotnikov's profile on LinkedIn

Follow Dmitry Sotnikov at Twitter

My Recent Tweets

Archives

See you at:

Legal

The posts on this blog are provided “as is” with no warranties and confer no rights. The opinions expressed on this site are mine and mine alone, and do not necessarily represent those of my employer Quest Software or anyone else for that matter. All trademarks acknowledged.

© 2007 Dmitry Sotnikov

Pages

 

July 2007
M T W T F S S
« Jun   Aug »
 1
2345678
9101112131415
16171819202122
23242526272829
3031