Generate secure and strong Random Passwords with PowerShell

PowerShell

When you’re scripting with PowerShell, there are a lot of times that you need to generate a password or secure string that you can use for your purposes. for example, you might want to create a bunch of Active Directory users or Office365/Exchange mailboxes and you want to set a random secure password for that account. I’ve seen a lot of sysadmins that are generating any secure strings such as passwords using an online service or other password generator application, manually.

In this post, I’m going to demonstrate different ways that you can use to generate a strong random password with PowerShell. in the end of this article, you’ll be able to implement the functionality as a function, and use it in your own PowerShell scripts to generate passwords or any other kind of secure strings, on the fly!

What are the options?

There are basically two ways that you can implement your Password generator :

  • Use the .Net Framework System.Web namespace
  • Write our own with pure PowerShell

Well, if you just search for this on the Internet, you will end up using .NET Framework. it’s powerful enough and also easy to implement however, it’s not that flexible if you ask. let’s see it in action, by writing a simple password generator function using System.Web namespace.

Function Generate-Password ([int]$PasswordLength){
	# Loading the required .Net Framework dll file for the System.Web Namespace:
	[Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
    # writing some info to PowerShell Console. the below line is unnecessary, but good practice!
	Write-Verbose "Generating $PasswordLength Character Random Password" -verbose
    # calling GeneratePassword method from the System.Web.Security.Membership class. notice that 
    # this method requires two integer inputs: Password Length and the minimum number of special characters {~!@#$%^&*()_+=-`}
	$RandomPassword = [System.Web.Security.Membership]::GeneratePassword($PasswordLength,2)
	return $RandomPassword
	}

The below image demonstrates a 20 character strong password in which is generated with the Function that we’ve just wrote above:

show how to execute the above cmdlet in PowerShell to generate password
20 character random password generated via the above PowerShell function

Everything seems good and it generates secure passwords for you, but you cannot control the character sets.

The only drawback with .Net-based method, would be not being able to generate human readable passwords.

Cons of using .Net assembly to generate secure strings such as passwords in PowerShell scripts

To be able to eliminate above limitation, We have to control what characters are allowed in the password, which leads us to write our own PowerShell Password Generator.

Function Create-RandomPassword (){
        [OutputType([String])]
        #[CmdletBinding(DefaultParameterSetName="PasswordLength")]
        [CmdletBinding()]
          Param (
        [parameter(Mandatory=$true)] #, ParameterSetName="PasswordLength")
        [Int]
        $Length = 15,

        [parameter(Mandatory=$false)]
        [switch]
        $ShowReadable
  )

            [string] $validChars1 = "$#%&@";
            [string] $validChars2 = "ABCDEFGHJKLMNPQRSTUVWXYZ";
            [string] $validChars3 = "abcdefghijkmnpqrstuvwxyz";
            [string] $validChars4 = "123456789";
            [string] $validChars  = $validChars1+$validChars2+$validChars3+$validChars4
            [Random] $random = [Random]::new();
            $chars = [char[]]::new($length);

            if ($Length -le 4){
            PS-Notify -NotifType Error -NotifMessage "Minimume Password Lengh must be at least 5 characters long!"
            throw ([System.ArgumentOutOfRangeException])
             }
            $chars[0] = $validChars1[$random.Next(0, $validChars1.Length)];
            $chars[1] = $validChars2[$random.Next(0, $validChars2.Length)];
            $chars[2] = $validChars3[$random.Next(0, $validChars3.Length)];
            $chars[3] = $validChars4[$random.Next(0, $validChars4.Length)];


            for ($i = 4; $i -lt $length; $i++){
                
                $chars[$i] = $validChars[$random.Next(0, $validChars.Length)];
            }

            $OutString = ($chars | Get-Random -Count $chars.Length) -join ''

            if ($ShowReadable){
                PS-Notify -NotifType Result -NotifMessage ([String]$OutString.ToCharArray())
                }
            return $OutString;
        }

Behrouz Amiri

I’m an author and SysAdmin. I worked for many well-known enterprises during my career, and still work for one, however, I always loved to write and contribute to the IT industry, and this led me here with you guys!

2 thoughts on “Generate secure and strong Random Passwords with PowerShell

  • September 22, 2020 at 1:21 am
    Permalink

    Been looking for this a while. Stackoverflow and like so’s are full of garbage functions all .net web based! This one rocks!! Thanks man

    Reply
    • September 23, 2020 at 7:00 pm
      Permalink

      I’m really glad you’ve found this helpful. how did you get here anyway!? we’ve just started this!

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.