Here’s one more reason to learn PowerShell and extend your scripting abilities with .NET Framework. In this quick sample we are going to use the .NET Framework Library Class Membership.GeneratePassword method to auto-generate a password. So, why would you spend time trying to build your own password generator application when .NET Framework gives you the method to cut down coding time. And, you can use this in PowerShell.
First, we need to look at the .NET method “System.Web.Security.Membership.GeneratePassword(X,Y)” that make this happen. For more information, here’s the link: http://msdn.microsoft.com/en-us/library/system.web.security.membership.generatepassword(VS.80).aspx
The Membership.GeneratePassword( X, Y ) will generates a random password of the specified length. Where X = number of characters to generate and Y = number of nonAlphanumericCharacters (punctuation characters). Both values supplied for this method need to be of type INT (integer).
Now, lets put these pieces together and demostrate that with a few lines of PowerShell we can use this .NET method to generate password. Because PowerShell doesn’t load all the .NET Framework Assemblies, we need to search and identify the the correct assembly we need to load. Then, we can do our PS magic the following way:
1. Load the assembly “System.Web”:
[Reflection.Assembly]::LoadWithPartialName(”System.Web”) # – For PowerShell V1 and V2
Add-Type -AssemblyName System.Web # – Only in PowerShell V2
2. Then, we use the “Membership.GeneratePassword( )” to produce the password:
[System.Web.Security.Membership]::GeneratePassword(8,3) # – You can change these valued but can’t never be blank.
Here’s the both sample:
This is just a start and gives an opportunity to build a decent script for generating passwords. Please don’t forget to search in Microsoft MSDN site for any information about .NET Framework: http://msdn.microsoft.com/en-us/library/default.aspx
Also, visit the Microsoft Script Center for valuable PowerShell scripts: http://technet.microsoft.com/en-us/scriptcenter/default.aspx
Have fun scripting!!