Created
July 28, 2017 13:17
-
-
Save skokhanovskiy/f8af6d4be574784ad80f42b2230f4696 to your computer and use it in GitHub Desktop.
Generate random string specified length
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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