PowerShell to Generate a Random Password

Are you looking for a quick way to create strong and secure passwords for multiple accounts or web applications? PowerShell is an easy-to-use terminal language that lets you generate random passwords quickly, helping save time and keeping your data safe. In this blog post, we’ll explore how to use PowerShell commands to generate random passwords with various length and complexity requirements. So let’s get started!

powershell generate random password

Why Use a PowerShell Random Password Generator?

Using a random password generator in PowerShell has several advantages. First and foremost, it ensures that the passwords generated are truly random, making them more secure compared to passwords created using predictable patterns or personal information. Additionally, a PowerShell random password generator allows for automation, making it ideal for scenarios where you need to generate multiple passwords quickly, such as when creating user accounts in Active Directory or setting up service accounts. By leveraging the power of PowerShell, you can create complex and unique passwords without needing external tools or manual intervention.

How to generate a random string in PowerShell?

To generate a random string in PowerShell, you can use the following script:

-join ((97..122) | Get-Random -Count 10 | ForEach-Object {[char]$_})

This will generate a random string of length 10, containing lowercase letters (a-z). E.g.

lyknbwdrxu

nlqgyuptac

iemrvdakzx

phxcvwdknb
Generate Random Password PowerShell

You can adjust the length of the string by changing the value of the -Count parameter. For example, to generate random characters of length 20, you would use -Count 20.

You can also modify the characters that are included in the string by adjusting the range of ASCII values passed to Get-Random cmdlet. For example, to generate a string containing uppercase letters, lowercase letters, and digits, you can use the following command:

$RandomString = -join ((48..57) + (65..90) + (97..122) | Get-Random -Count 10 | ForEach-Object {[char]$_})

This will generate a random password length of 10 characters, containing upper case letters and digits. To create a random string from given characters, use:

-Join("ABCDabcd&@#$%1234".tochararray() | Get-Random -Count 10 | % {[char]$_})

You can use this technique to generate random passwords of any length, containing any combination of characters. Let’s take a look at how to generate a random password in PowerShell by wrapping the script into a reusable function.

function New-RandomPassword {
    param (
        [Parameter(Mandatory=$true)]
        [int]$Length,
        [string]$Characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+[]{}|;:,.<>?'
    )
    
    $password = -join (1..$length | ForEach-Object { Get-Random -InputObject $characters.ToCharArray() })
    return $password
}

$Password = New-RandomPassword -Length 5 -Characters "abcdefghijklmnopqrstuvwxyz"
Write-host $Password

This method allows you to be more flexible in defining the character set, such as an array of lowercase characters to generate random passwords.

Custom Random Password Generator

If you prefer more control over the password generation process, you can create a custom random password generator using PowerShell. This method allows you to define the character sets and complexity rules according to your needs. Here’s an example of a custom random password generator function in PowerShell:

function Generate-RandomPassword {
    param (
        [Parameter(Mandatory)]
        [int] $length
    )

    $charSet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.ToCharArray()

    $rng = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
    $bytes = New-Object byte[]($length)
 
    $rng.GetBytes($bytes)
 
    $result = New-Object char[]($length)
 
    for ($i = 0 ; $i -lt $length ; $i++) {
        $result[$i] = $charSet[$bytes[$i]%$charSet.Length]
    }

    return -join $result
}

Generate-RandomPassword 10

In this example, the Generate-RandomPassword function generates a random password by selecting characters from the specified character set variable using a loop. In this case, the character set includes lowercase and uppercase letters and digits. You can modify the character set to include special characters or remove certain character types based on your requirements.

Random Password Generator using PowerShell

A robust password should include uppercase, lowercase, special characters, and numbers. It’s not always easy to come up with these passwords on the spot, so you may want to consider generating a random password. Here’s how to create a random password in PowerShell.

Function Get-RandomPassword
{
    #define parameters
    param([Parameter(ValueFromPipeline=$false)][ValidateRange(1,256)][int]$PasswordLength = 10)

    #ASCII Character set for Password
    $CharacterSet = @{
            Lowercase   = (97..122) | Get-Random -Count 10 | % {[char]$_}
            Uppercase   = (65..90)  | Get-Random -Count 10 | % {[char]$_}
            Numeric     = (48..57)  | Get-Random -Count 10 | % {[char]$_}
            SpecialChar = (33..47)+(58..64)+(91..96)+(123..126) | Get-Random -Count 10 | % {[char]$_}
    }

    #Frame Random Password from given character set
    $StringSet = $CharacterSet.Uppercase + $CharacterSet.Lowercase + $CharacterSet.Numeric + $CharacterSet.SpecialChar

    -join(Get-Random -Count $PasswordLength -InputObject $StringSet)
}

#Call the function to generate random password of 8 characters
Get-RandomPassword -PasswordLength 8

#Sample Output: glx`FC>Y

This function will generate a completely randomized secure password that meets all modern security standards and requirements (A new password with a combination of uppercase characters, and lower case alphabets, numbers, and special characters is ideal!). Call the Get-RandomPassword function to generate a 10-character long random password.

generate random password powershell

Using Built-in System.Web.Security.Membership Class

One of the simplest and most effective ways to generate random passwords in PowerShell is by utilizing the built-in System.Web.Security.Membership class. This class provides a method called GeneratePassword() that allows you to generate random passwords with specified lengths and complexity.

Here is a simple way to create a secure random password using .NET framework method:

[System.Web.Security.Membership]::GeneratePassword(10,2)

This command generates a random 10-character password containing two non-alphanumeric characters (e.g., %&). If you want more or fewer characters for your password, simply change the number 10 in the command to whatever length you desire (e.g., 10).

function Generate-Password {
    param (
        [Parameter(Mandatory)]
        [int] $length,
        [int] $amountOfNonAlphanumeric = 1
    )
    Add-Type -AssemblyName 'System.Web'
    return [System.Web.Security.Membership]::GeneratePassword($length, $amountOfNonAlphanumeric)
}

Generate-Password 10

The Generate-Password function takes two parameters: length and amountOfNonAlphanumeric. The length parameter determines the length of the password, while the amountOfNonAlphanumeric parameter specifies the number of non-alphanumeric characters in the password. By adjusting these parameters, you can generate passwords that meet your specific requirements.

PowerShell Random password one-liner: -join([char[]](33..122) | Get-Random -Count 10)

The created passwords can be converted to secure passwords using the following:

$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force

Conclusion:

Creating strong passwords is an essential part of staying safe online in today’s world. Fortunately, there’s no need to spend hours trying to think of complex passwords when you can quickly generate them using PowerShell commands! With just a few simple steps, you can quickly create completely randomized passwords that meet current security standards – and keep prying eyes away from your data!

Remember, generating strong passwords is just one aspect of maintaining a secure environment. It’s equally important to store passwords securely, implement access controls, and regularly update and rotate passwords to minimize the risk of unauthorized access.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

4 thoughts on “PowerShell to Generate a Random Password

  • Your Uppercase and Lowercase character set entries are switched around.

    Reply
  • Your Get-RandomPassword function generates passwords has much lower entropy than what a truely random password would use, because it only allows each character to appear no more than once in the generated password.

    Reply
    • True! The Get-Random doesn’t ensure cryptographically secure randomness. Use the other methods in the article.

      Reply

Leave a Reply

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