Skip to content

Instantly share code, notes, and snippets.

@skokhanovskiy
Created July 28, 2017 13:17
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 skokhanovskiy/f8af6d4be574784ad80f42b2230f4696 to your computer and use it in GitHub Desktop.
Save skokhanovskiy/f8af6d4be574784ad80f42b2230f4696 to your computer and use it in GitHub Desktop.
Generate random string specified length
function Get-RandomString
{
[CmdletBinding()]
param
(
[Parameter(Position = 0, Mandatory = $true)]
[UInt32] $Length,
[Parameter()]
[String] $Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
)
$CharsLength = $Chars.Length
if ($CharsLength -gt 0)
{
try
{
$Result = [System.Char[]]::new($Length)
$Random = [System.Random]::new()
for ($I = 0; $I -lt $Length; $I++)
{
$Result[$I] = $Chars[$Random.Next($CharsLength)]
}
}
catch
{
throw $_
}
}
else
{
$Result = [System.String]::Empty
}
return [System.String]::new($Result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment