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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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.