#PowerShell script to generate a new Random Password

Here is a #PowerShell script that generates a new Random Password – Complex OR Simple. Need to pass parameter variables for Password Length and a Boolean for Complexity.

Usage : New-RandomPassword -PwdLength 20 -Complex $true

Usage : New-RandomPassword -PwdLength 20 -Complex $false

Function New-RandomPassword
{
    [CmdletBinding(SupportsShouldProcess=$True)]

    Param(
        [int]$PwdLength,
        [boolean]$Complex
    )

    #Characters Sets to be used for Password Creation

    $CharSimple = "A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z","1","2","3","4","5","6","7","8","9","0","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z” 
    $CharComplex = "A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z","1","2","3","4","5","6","7","8","9","0","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z”,"!","_" 
    $CharNumbers = "1","2","3","4","5","6","7","8","9","0"
     
    #Verify if the Password contains at least 1 digit character

    $ContainsNumber = $False
    $Pwd = $Null
     
    #Sets which Character Array to use based on $Complex

    if ($Complex)
                    {$PwdCharacters = $CharComplex}
    else
                    {$PwdCharacters = $CharSimple}
   
    #Loop to actually generate the password

    for ($i=0;$i -lt $PwdLength; $i++)
        {$c = Get-Random -InputObject $PwdCharacters
            if ([char]::IsDigit($c))
        {$ContainsNumber = $True}
         $Pwd += $c}
    
    #Check to see if a Digit was seen, if not, fixit

    if ($ContainsNumber)
        {
            Return $Pwd
        }
        else
        {
            $Position = Get-Random -Maximum $PwdLength
            $Number = Get-Random -InputObject $CharNumbers
            $PwdArray = $Pwd.ToCharArray()
            $PwdArray[$Position] = $Number
            $Pwd = ""
            foreach ($s in $PwdArray)
            {
                $Pwd += $s
            }
        Return $Pwd
       
    }
# Usage : New-RandomPassword -PwdLength 20 -Complex $true
# Usage : New-RandomPassword -PwdLength 20 -Complex $false

You may also use a more advanced .NET Class as below

Add-Type -AssemblyName System.Web
$PasswordLength = 12
$SpecialCharCount = 3
[System.Web.Security.Membership]::GeneratePassword($PasswordLength, $SpecialCharCount)

Cheers 🙂

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 )

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

%d bloggers like this: