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 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