Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Last active January 20, 2021 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsscoder/04979a698f0deccfc49b6489056c4771 to your computer and use it in GitHub Desktop.
Save gsscoder/04979a698f0deccfc49b6489056c4771 to your computer and use it in GitHub Desktop.
PowerShell function to generate alphanumeric string
# PS> 20 | Get-RandomString -Alphanumeric $false -NoQuotes $true
# PS> p({BFhlH*}KG#S{i{Ih5
function Get-RandomString {
[OutputType([string])]
param(
[Parameter(Mandatory, ValueFromPipeline)] [int] $Length,
[bool] $Alphanumeric = $true,
[bool] $NoQuotes = $false
)
[char[]] $alphanumericChars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
[char[]] $allChars = "abcdefghijklmnopqrstuvwxyz0123456789!`"#$%&'()*@[\\]^_``{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZ"
[char[]] $allCharsNoQuotes = 'abcdefghijklmnopqrstuvwxyz0123456789!#$%&()*@[\\]^_{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if ($NoQuotes -and $Alphanumeric) { throw '-NoQuotes cannot be true when -Alphanumeric is true.' }
$chars = if ($Alphanumeric) { $alphanumericChars } else {
if ($NoQuotes) { $allCharsNoQuotes } else { $allChars } }
$result = [System.Text.StringBuilder]::new($Length)
$random = [System.Random]::new()
for ($i = 0; $i -lt $Length; $i++) {
$result.Append($chars[$random.Next($chars.Length)]) | Out-Null
}
$result.ToString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment