PowerShell Random Password Function

By | 2022-08-05

Generating a password with PowerShell is relatively easy if you leverage a particular method of .Net, System.Web.Security.Membership.

Add-Type -AssemblyName System.Web
[System.Web.Security.Membership]::GeneratePassword(8,2)

Simple and to the point. But below is a pretty good function to do something similar, if you are curious about string operations with PowerShell.

function Get-RandomPassword($length)
{
    $length-=1
    $lower = 'abcdefghijklmnopqrstuvwxyz'
    $upper = $lower.ToUpper()
    $number = 0..9
    $special='~!@#$%^&*()_+|}{[]\'
    $chars = "$lower$special$upper".ToCharArray()

$pass = Get-Random -InputObject $chars -Count $length
    $digit = Get-Random -InputObject $number
    
    (-join $pass).insert((Get-Random $length),$digit)
}

# example
Get-RandomPassword -Length 20

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

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.