Search Tools Links Login

PowerShell Random Password Function


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

About this post

Posted: 2022-08-05
By: dwirch
Viewed: 168 times

Categories

Scripting

Powershell

PowerShell Code Cache

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.