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.

#function starts here
function New-RandomPassword()
{
#specifies the default maximum no of characters to be generated for password
#can be override by passing parameter values while calling function
param(
[int]$maxChars=8
)
#specifies a new empty password
$newPassword = ""
#defines random function
$rand = New-Object System.Random
#generates random password
0..$maxChars | ForEach-Object {$newPassword += [char]$rand.Next(33,126)}
return $newPassword
}
#function ends here

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 )

Connecting to %s