Skip to content

Instantly share code, notes, and snippets.

@Digiover
Last active April 5, 2026 07:48
Show Gist options
  • Select an option

  • Save Digiover/d74a76efedf1e84ddaf947b7284dfe2a to your computer and use it in GitHub Desktop.

Select an option

Save Digiover/d74a76efedf1e84ddaf947b7284dfe2a to your computer and use it in GitHub Desktop.
Easily create a random string (or secure password) using PowerShell. Add to your PS profile
function Get-RandomString {
param (
[CmdletBinding(PositionalBinding=$false)]
[Parameter(Position=0)]
[ValidateRange(8, 256)]
[int] $Length = 20,
[Parameter(Position=1)]
[validateset("AlphaNumeric", "SQLCompliant")]
[string]$Compliancy
)
$Characters = [char[]](65..90) # A..Z
$Characters += [char[]](97..122) # a..z
$Characters += [char[]](48..57) # 0..9
Switch ($Compliancy){
"AlphaNumeric" {
}
"SQLCompliant" {
$Characters += [char[]](33) #!
$Characters += [char[]](35..37) # #$%
}
default {
$Characters += [char[]](33..47) # !"#&%'()*+,-./
}
}
if($PSVersionTable.PSVersion.Major -eq 5) {
$Password = @()
For ($i = 0; $i -lt $Length; $i++) {
$Password += $Characters | Get-Random
}
} else {
$Password = @()
For ($i = 0; $i -lt $Length; $i++) {
$Password += $Characters[[System.Security.Cryptography.RandomNumberGenerator]::GetInt32($Characters.Count)]
}
}
return -join $Password
}
@Digiover
Copy link
Copy Markdown
Author

Digiover commented Feb 6, 2024

Examples (when added to $PROFILE):

PS > get-randomString 20
SoAah#MwvY&B'M8GvFGI
PS > get-randomString 20 sqlCompliant
eO6sPxRAp789JZRAlelP
PS > 1..10 | % { Get-RandomString 20 SQLCompliant }
TTFoxZ87txhnbmIU9q5A
R4vWWvwgfP0qIt4XYu9o
s!f%CdUvlCI$zQrCFqSc
1TPCtleGZwHA0wesEGTg
eETPS96UevEjT6SQkKRP
vrPkAeR7Eb$3yN5zn42o
U#qpiEKi3CzdqM9EtHiG
pBmcscaeYIWl9I3BQqm!
xJu2c4vnef5MD1$XsgtE
$JbHI2i!eUTIlW9jlt4g
PS > $numb = 10; for ($i=1; $i -le $numb; $i++) { Get-RandomString 20 }
r6wNBT9Cj!qw9Xor!YME
#'#l&ElZtFCeJ")#%U.v
Mo4Y(Qf9w0$ZYcn25x6.
*C7m"ZXSEpuPSq53qbyu
8v2u+#*UM"OB27"5ykiP
cySi)CXY+Pyav!yx,t2J
HwmzRI%P0tFoz($TlH)W
#bkCV5VtYq4(xqNcwaax
w&mWb6Tga$+KGL(/"B)9
#UJPrdnot)$67umHIdGo

@Digiover
Copy link
Copy Markdown
Author

Digiover commented Mar 6, 2026

Update: Substituted Get-Random with RandomNumberGenerator::GetInt32() for a more Cryptographically Secure Pseudo-Random Number Generator (CSPRNG). This requires Powershell 7.x

@Digiover
Copy link
Copy Markdown
Author

Digiover commented Apr 5, 2026

Added a PowerShell version check (5.1 uses Get-Random) and fixed [char] ranges which didn't work in PS5.1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment