Generate Random Password Powershell Function

I recently saw a tip from that prompted me to make the below function. It generates random passwords with the length and number of special characters you specify. I hope someone else finds it useful.

If you are wondering how to include libraries in your code see below.

# Here is how your include

Here is the function to generate passwords

#Generate Random Password Function
# By David Cearlock
# Based on Tip From

function generate-password($length,$special){

# $length is the number of characters of the new password
# The default length is 8

# $special is the number of special characters the new password should contain
# The default number of special characters is 4

$Assembly = Add-Type -AssemblyName System.Web

if($length -ne $null -and $special -ne $null){

$password = [System.Web.Security.Membership]::GeneratePassword($length,$special)


if($length -ne $null -and $special -eq $null){

$password = [System.Web.Security.Membership]::GeneratePassword($length,4)


if($length -eq $null -and $special -ne $null){

$password = [System.Web.Security.Membership]::GeneratePassword(8,$special)


if($length -eq $null -and $special -eq $null){

$password = [System.Web.Security.Membership]::GeneratePassword(8,4)


return $password


Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Login with Facebook: