Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Powershell: Generate a random Alphanumeric string
# Generate a random Alphanumeric string
Function Get-RandomAlphanumericString {
Param (
[int] $length = 8
Write-Output ( -join ((0x30..0x39) + ( 0x41..0x5A) + ( 0x61..0x7A) | Get-Random -Count $length | % {[char]$_}) )
# Write-Host ("Alfa Beta " | Tee-Object -Variable txt) ($txt.length)
Write-Host "A: "(Get-RandomAlphanumericString | Tee-Object -variable teeTime ) ("len=$($teeTime.length)")
Write-Host "B: "(Get-RandomAlphanumericString -length 22 | Tee-Object -variable teeTime ) ("len=$($teeTime.length)")
Copy link

ediulia commented Jan 18, 2021

Here is my final function with the reference to the source, which I modified a bit
Function Generate-Password

Generate-Password -Size $PassParmINIObject.Values.MinLength -CharSets ULN -Exclude ABCde123
[Int]$Size = 8,
[Char[]]$CharSets = "ULNS",
$SpecialCharactersList # = '!"#$%&''()*+,-./:;<=>?@[]^_`{|}~' # Default if the characters list is not set in passparm.ini

# Debug output of Special Characters received to the function instead of the default

# Write-Host $SpecialCharactersList -ForegroundColor Red
$Chars = @(); $TokenSet = @()

If (!$TokenSets) {$Global:TokenSets = @{
    U = [Char[]]'ABCDEFGHIJKLMNOPQRSTUVWXYZ'                                #Upper case
    L = [Char[]]'abcdefghijklmnopqrstuvwxyz'                                #Lower case
    N = [Char[]]'0123456789'                                                #Numerals
    S = [Char[]]$SpecialCharactersList                                      #Symbols

$CharSets | ForEach {
    $Tokens = $TokenSets."$_" | ForEach {If ($Exclude -cNotContains $_) {$_}}
    If ($Tokens) {
        $TokensSet += $Tokens
        If ($_ -cle [Char]"Z") {$Chars += $Tokens | Get-Random}             #Character sets defined in upper case are mandatory

While ($Chars.Count -lt $Size) 
        $Chars += $TokensSet | Get-Random

        # Debug output of random chars to be sent to the string and string length
        # Write-Host "$Chars : $($Chars.Count) ######## Output Here ######### $Size" -ForegroundColor Red
($Chars | Sort-Object {Get-Random}) -Join ""                                #Mix the (mandatory) characters and output string

} # End of Function Generate-Password

Copy link

Great! Thanks for improving this tread!

Copy link

This is a great solution to my issue of generating a password without special characters!

The only concern I had was that characters could not be re-used, which drastically reduces the randomness of the strings it makes. So I worked out a solution that hopefully can help some other people frustrated by the GeneratePassword forced random characters.

The 62 Character limit is because the Get-Random function will not get the same character twice. When it gets, it essentially pops that item out of the array and can no longer choose it.

Here is a way around it which seems to work quite well.

$length = 72
$pwd = ""; do { $pwd = $pwd + ((0x30..0x39) + (0x41..0x5A) + (0x61..0x7A) | Get-Random | % {[char]$_}) } until ($pwd.length -eq $length)

This may or may not use every character in the array, as the array is refreshed after each letter is added.

Btw, first time posting on git. Woot!

Copy link

me-suzy commented Apr 10, 2021

ok, in powershell, does anyone know how to make a shuffle words, on several txt files, search and replace like this ?

Copy link

BeMor81 commented Jul 8, 2022

As others have said, the maximum length is 62 and also the characters are never reused so greatly reduces the complexity of the string. The below works around these issues

Write-Output ( -join ($(for($i=0; $i -lt $length; $i++) { ((0x30..0x39) + ( 0x41..0x5A) + ( 0x61..0x7A) | Get-Random | % {[char]$_}) })) )

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