How to customize password generation

You can use standard random function call

[System.Web.Security.Membership]::GeneratePassword(8,2) # (lengh,complexity)

In that case, you get simple but unpredictable range of symbols which can conflict with your password policy.

Or you can customise it using specific logic. For example, you need at least 1 symbol from each range of characters: a-z, A-Z and 0-9. Additionally, you can control length of the generated password. Here is code snippet:

$sourcedata -eq $NULL;”48..57,65..90,97..122″.Split(‘,’) | Where {$_ -ne “”} | % {iex $_} | %{$sourcedata+=,[char][byte]$_ }
$charsLower=97..122 | %{ [Char] $_ }
$charsUpper=65..90 | %{ [Char] $_ }
$charsNumber=48..57 | %{ [Char] $_ }
Function Test-StringContents([String] $test, [Char[]] $chars)
foreach ($char in $test.ToCharArray())
if ($chars -ccontains $char)
return $true
return $false
Function GET-Temppassword() {
For ($loop=1; $loop –le $length; $loop++) {
$TempPassword+=($sourcedata | GET-RANDOM)
if( (Test-StringContents $TempPassword $charsLower) `
-and (Test-StringContents $TempPassword $charsUpper) `
-and (Test-StringContents $TempPassword $charsNumber) ){
return $TempPassword
return GET-Temppassword -length $length

Here is some tests:

GET-Temppassword –length 7
GET-Temppassword –length 12
GET-Temppassword #default lenght 10 symbols


About Andrew Butenko
This entry was posted in PowerShell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

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

Google+ photo

You are commenting using your Google+ 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