Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Powershell: Generate a random Alphanumeric string
# Generate a random Alphanumeric string
Function Get-RandomAlphanumericString {
[CmdletBinding()]
Param (
[int] $length = 8
)
Begin{
}
Process{
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)")
@KEV1L

This comment has been minimized.

Copy link

@KEV1L KEV1L commented Jul 3, 2018

Very helpful, thanks!

@j-i-m-s-t-e-r

This comment has been minimized.

Copy link

@j-i-m-s-t-e-r j-i-m-s-t-e-r commented Mar 18, 2020

teeTime Like it!

@NadalinVini

This comment has been minimized.

Copy link

@NadalinVini NadalinVini commented Sep 25, 2020

great!

@ediulia

This comment has been minimized.

Copy link

@ediulia ediulia commented Nov 13, 2020

A great solution for me! Thanks

@marcgeld

This comment has been minimized.

Copy link
Owner Author

@marcgeld marcgeld commented Nov 15, 2020

Great that you all find the code useful!

@ediulia

This comment has been minimized.

Copy link

@ediulia ediulia commented Nov 19, 2020

Thanks. Pretty simple and useful. But sometimes it misses the numbers,,,
Like in this output:
JbTWkLOHJrWs

@marcgeld

This comment has been minimized.

Copy link
Owner Author

@marcgeld marcgeld commented Nov 19, 2020

Yes, the selection is randomized and the string might not contain numbers. Likewise it could be a string with only numbers, which is more likely if you generate a short string. If you need a string with more even distribution of word character and digits there are likely better ways to generate then using my function.

@ediulia

This comment has been minimized.

@Kipjr

This comment has been minimized.

Copy link

@Kipjr Kipjr commented Dec 3, 2020

Any idea why there is a limit of 62 chars?

@marcgeld

This comment has been minimized.

Copy link
Owner Author

@marcgeld marcgeld commented Dec 3, 2020

The function creates string in the intervals 0-9A-Z a-z and then sample randomize character from that string. Why Get-Random stops sampling after 62 chars I don't know, but I guess it is dependent on the string length. The function was created to generate fairly randomized short string to be included in some test files back in history. I don't think I have used it to generate any strings longer then 10 chars so I didn't know about the 62 chars limit. I don't write any things for PowerShell at this moment and don't have easy access to a Windows environment so I'm unable to dig in and find out why the 62 chars limit but If anybody knows feel free to write a comment here.

@andreiv3103

This comment has been minimized.

Copy link

@andreiv3103 andreiv3103 commented Jan 15, 2021

Any idea why there is a limit of 62 chars?

I think I know why:

image

If you need a longer string (as I needed in a project), you can just add the characters again, like this:

image

@ediulia

This comment has been minimized.

Copy link

@ediulia ediulia commented Jan 18, 2021

Here is my final function with the reference to the source, which I modified a bit
Function Generate-Password
{
<#
https://stackoverflow.com/questions/37256154/powershell-password-generator-how-to-always-include-number-in-string

.EXAMPLE
Generate-Password -Size $PassParmINIObject.Values.MinLength -CharSets ULN -Exclude ABCde123
#>
Param
(
[Int]$Size = 8,
[Char[]]$CharSets = "ULNS",
[Char[]]$Exclude,
$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
#pause
$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

@marcgeld

This comment has been minimized.

Copy link
Owner Author

@marcgeld marcgeld commented Jan 18, 2021

Great! Thanks for improving this tread!

@GoldeneyesII

This comment has been minimized.

Copy link

@GoldeneyesII GoldeneyesII commented Feb 5, 2021

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!

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