Skip to content

Instantly share code, notes, and snippets.

@Digiover
Created June 7, 2023 08:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Digiover/d74a76efedf1e84ddaf947b7284dfe2a to your computer and use it in GitHub Desktop.
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
# Add to your PS profile to create random strings / secure passwords
# from within your PowerShell shell.
#
# Source / Author: Daniel Kåven
# https://teams.se/powershell-script-generate-a-random-password/
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..[char]90 # A..Z
$Characters += [char]97..[char]122 # a..z
$Characters += [char]48..[char]57 # 0..9
Switch ($Compliancy){
"AlphaNumeric" {
}
"SQLCompliant" {
$Characters += [char]33 #!
$Characters += [char]35..[char]37 # #$%
}
default {
$Characters += [char]33..[char]47 # !"#&%'()*+,-./
}
}
$Password = @()
For ($i = 0; $i -lt $Length; $i++) {
$Password += $Characters | Get-Random
}
return -join $Password
}
@Digiover
Copy link
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

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