Tuesday, March 10, 2020

Generate random password in Powershell

$characters = 'abcdefghkmnprstuvwxyzABCDEFGHKLMNPRSTUVWXYZ'
$nonchar = '123456789!$%&?+#'
$length = 15  #The total length will be 15, the last two characters are nonchar.

# select random characters
$random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
$random2 = 1..2 | ForEach-Object { Get-Random -Maximum $nonchar.length }

$private:ofs= ""
$password = [String]$characters[$random] + [String]$nonchar[$random2]
return $password