Share via


How to Generate a Secure Random Password using PowerShell

The goal of this post is to show you how you can use Windows PowerShell to call .NET Method().

Simply, all you have to know is the namespace, assembly name, and the method name.

So, how can I do that ?!

  • Load the required assembly in your PowerShell console using [Reflection.Assembly]::LoadWithPartialName("AssemblyName")
  • Call you Method [namespace]::Method(Parameters)

In the following example I'll use Membership.GeneratePassword  Method to generate a Complex Passwords randomly

# namespace: System.Web.Security # assembly: System.Web (in System.Web.dll) # method: GeneratePassword(int length, int numberOfNonAlphanumericCharacters)

#Load "System.Web" assembly in PowerShell console [Reflection.Assembly]::LoadWithPartialName("System.Web") #Calling GeneratePassword Method [System.Web.Security.Membership]::GeneratePassword(10,0)

Regards
Sherif Talaat (Twitter: @Sheriftalaat)

Comments

  • Anonymous
    January 01, 2003
    That's very nice! I like to have a selection uf passwords, so I do this: 1..10 |%{[System.Web.Security.Membership]::GeneratePassword(10,0)} Karl

  • Anonymous
    January 01, 2003
    NOTE: To stop randomly falling foul of the strong passwords law use a positive integer in position number 2 of the function call. For example: 16,2 .

  • Anonymous
    February 10, 2014
    This is great, How can I assign that exact generated password? i.e $AccountPass=[Random Password here]

  • Anonymous
    March 25, 2014
    $AccountPass = $([System.Web.Security.Membership]::GeneratePassword(16,8))

  • Anonymous
    July 16, 2014
    Worked for me :)