powershellpasswordsgenerator

PowerShell - Password Generator - How to always include number in string?


I have the following PowerShell script that creates a random string of 15 digits, for use as an Active Directory password.

The trouble is, this works great most of the time, but on some occasions it doesn't use a number or symbol. I just get 15 letters. This is then not usable as an Active Directory password, as it must have at least one number or symbol in it.

$punc = 46..46
$digits = 48..57
$letters = 65..90 + 97..122
$YouShallNotPass = get-random -count 15 `
-input ($punc + $digits + $letters) |
% -begin { $aa = $null } `
-process {$aa += [char]$_} `
-end {$aa}

Write-Host "Password is $YouShallNotPass"

How would I amend the script to always have at least one random number or symbol in it?

Thank you.


Solution

  • You could invoke the Get-Random cmdlet three times, each time with a different input parameter (punc, digit and letters), concat the result strings and shuffle them using another Get-Random invoke:

     (Get-Random -Count 15 -InputObject ([char[]]$yourPassword)) -join ''
    

    However, why do you want to reinvent the wheel? Consider using the following GeneratePassword function:

    [Reflection.Assembly]::LoadWithPartialName("System.Web")
    [System.Web.Security.Membership]::GeneratePassword(15,2)
    

    And to ensure, it contains at least one random number (you already specify the number of symbols):

    do {
       $pwd = [System.Web.Security.Membership]::GeneratePassword(15,2)
    } until ($pwd -match '\d')