How to create Random Passwords with PowerShell

I created this PowerShell function to quickly generate random passwords for end-users or create random passwords for service accounts. The code is based on Ed Wilson, Microsoft Scripting Guy post, I just modified it for my needs and turned it into a function.
Function Get-RandomPassword{
<#
.SYNOPSIS
Get-TempPassword the function generates a random password with a few rule sets. I have excluded familiar miss-type characters like "I" and "l".
.DESCRIPTION
The function is used to generate a random password quickly, the password begins and ends with a letter and has one special character
.LINK
https://devblogs.microsoft.com/scripting/generating-a-new-password-with-windows-powershell/
https://ascii.cl/
.NOTES
Created By Ronnie Rosal
Version 2
-Added ValidationSet Mode ServiceAccount, max password length for service account is 20. Linux systems will truncated password over 20 charaters.
.PARAMETER KEY
Length how long do you want the password, default is 12 characters.
.EXAMPLE
PS C:\Windows\system32> Get-RandomPassword -Length 20
QKvo5Ty@\ud\nQ]8ec-z
PS C:\Windows\system32> Get-RandomPassword -Length 5
TGM!b
#>
[CmdletBinding()]
Param (
[Parameter(Position = 0,Mandatory = $False)]
$Length=12,
[Parameter(Position = 0,Mandatory = $False)]
[ValidateSet("ServiceAccount","TempPassword")]
$Mode = "RandomPassword",
[Parameter(Position = 0,Mandatory = $False)]
$Sourcedata= "NULL")
$FunctionName = $MyInvocation.InvocationName
If($Mode -eq "RandomPassword"){
$Length = $Length - 3
}
If($Mode -eq "ServiceAccount" -and $Length -gt 20){
Write-Warning "Password length is Greater Than 20, setting length to 20"
$Length = 20 - 3
}
$StartChar = [Char[]] "ABCDEFGHJKMNOPQRSTUVWXYZ"
$EndChar = [Char[]] "abcdefghjkmnopqrstuvwxyz"
$PasswordStart = ($StartChar | Get-Random -Count 1)
$PasswordEnd = ($EndChar | Get-Random -Count 1)
If($Sourcedata -eq "NULL"){
$Sourcedata=$null
For ($a=33;$a -le 48;$a++) {$SpecialChar +=,[char][byte]$a }
For ($a=50;$a -le 72;$a++) {$Sourcedata +=,[char][byte]$a }
For ($a=74;$a -le 75;$a++) {$Sourcedata +=,[char][byte]$a }
For ($a=77;$a -le 94;$a++) {$Sourcedata +=,[char][byte]$a }
For ($a=97;$a -le 104;$a++) {$Sourcedata +=,[char][byte]$a }
For ($a=106;$a -le 123;$a++) {$Sourcedata +=,[char][byte]$a }
For ($a=125;$a -le 126;$a++) {$Sourcedata +=,[char][byte]$a }
}
If($SpecialChar -eq $NULL){
$SpecialChar=$null
For ($b=33;$b -le 48;$b++) {$SpecialChar +=,[char][byte]$b }
}
For ($loop=1; $loop -le $Length; $loop++) {
$TempPassword+=($Sourcedata | GET-RANDOM)
}
return $PasswordStart + $TempPassword + ($SpecialChar | GET-RANDOM) + $PasswordEnd
}
Why build a function to create random passwords?
The Get-TempPassword the function generates a random password with a few rule sets. I have excluded familiar miss-type characters like "I" and "l". I also added the rule to ensure the password begins and ends with a letter and has one special character.



