Generate random password using PowerShell

For this purpose, we can use the System.Random library in .Net and use Next() to generate a random value out of the specified values. More details on the function can be found at https://msdn.microsoft.com/en-us/library/2dx6wyd4(v=vs.110).aspx.

Below function can be used to generate a password for given no of characters. If not specified, it will generate a password with 8 characters.

To call the function, we can simply use code like this:

PS C:\users\mgoyal\Documents\VSCode> $pass = New-RandomPassword 12
 PS C:\users\mgoyal\Documents\VSCode> $pass
 A(Djw#[\STDZ)

Note that we use the [char] value for the random integer value returned between integers of 33 and 126. If you want to exclude or include certain characters, you need to refer integer codes as per ascii table.

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 )

Google+ photo

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

Connecting to %s