...Because someone's gotta tell the story...


To return to the main Blog List, click Full Blog Listing.



Expanding the Random Character Generator

Saturday, June 22, 2013 in Powershell (Views: 1188)
So, let's expand on something from earlier, the Random Character Generator. In this blog, the script will provide a few examples:

1. Multiple parameter values in a function
2. Returning a value in a function

Because I am using this to create file names, I added an additional piece which says if I wanted to use all lower, upper, numbers, or just all characters (excluding special, of course).

Here is the script:
Function CreateRand {param([int]$NumChars, [string]$ConvType)
if ($ConvType.ToUpper() -eq "U"){
elseif ($ConvType.ToUpper() -eq "L"){
$InclChars = "abcdefghkmnprstuvwxyz1234567890"
elseif ($ConvType.ToUpper() -eq "N"){
$InclChars = "1234567890"
elseif ($ConvType.ToUpper() -eq "A"){
$InclChars = "abcdefghkmnprstuvwxyzABCDEFGHKLMNPRSTUVWXYZ123456789"

$Private:OFS = ""
$RandomChars = 1..$NumChars| ForEach-Object {Get-Random -Maximum $InclChars.length}
return ([String]$InclChars[$RandomChars]).Trim()

Although it looks obvious, the parameters of CreateRand:
1. How long of a string do you want? I chose 8 characters.
2. What type of characters do you want to use? U for all upper, L for all Lower, N for just numbers, and A for just everything.

To call this? Simple:
$tmpString=CreateRand 8 u

..and of course, use $tmpString however you like.


Related Blogs You May Be Interested In:

To leave a comment, please log in and/or register.