Generate Random String in PowerShell

Generate random String in PowerShell

Using [System.Guid] Class

To generate a random string in PowerShell:

  • Create a globally unique identifier using the NewGuid() method.
  • Use the ToString() method to transform the GUID (created in the previous step) to String format.
  • Use the Write-Host cmdlet to print the random string.

The New-Guid() is a static method of [System.Guid] class which we used to create a random GUID (Globally Unique Identifier). We use this method if we are required to create a unique ID in a script.

Next, we chained the ToString() method with New-Guid() to change its type to String that we stored in the $randomString variable. Finally, we used the Write-Host cmdlet to print the value of $randomString to the PowerShell console.

Using .NET RNGCryptoServiceProvider Class

To generate a random string in PowerShell:

  • Use the New-Object cmdlet to create a byte array.
  • Use the New-Object cmdlet to create an object of the .NET RNGCryptoServiceProvider class.
  • Use the GetBytes() method to fill the byte array (created in the first step) with random bytes.
  • Use ToBase64String() method to transform the byte array to base64-encoded string.
  • Use the Write-Host cmdlet to the transformed string to the PowerShell console.

First, we used the New-Object cmdlet to create a byte type array and stored its reference in the $randomBytesArray variable. This array will hold random bytes that we will generate later in the code. The New-Object cmdlet belongs to the Microsoft.PowerShell.Utility module and is used to create objects.

Again, we used the New-Object cmdlet to create an instance of the RNGCryptoServiceProvider class and stored it in the $rngObject variable. Why created this object? Because the RNGCryptoServiceProvider class helps to generate random bytes in a cryptographically secure way. We used the GetBytes() method, which took $randomBytesArray as a parameter and filled it with random bytes.

After that, we used the ToBase64String() method of the [System.Convert] class, which took $randomBytesArray as a parameter, converted it to the base64-encoded string and stored in $randomString variable. Finally, we used the Write-Host cmdlet to print the $randomString on the PowerShell console.

Using System.Random with For and ForEach Loop

To generate a random string of 10 characters in PowerShell:

  • Chain the ToCharArray() method with a string value to create an array of characters.
  • Use the New-Object cmdlet to create an instance of the System.Random class.
  • Use the for loop to perform the same jobs 10 times.
  • For every iteration:
    • Create a random index using the Next() method.
    • Retrieve the character from the random index created in the previous step.
    • Use += to concatenate the current character retrieved from the specified random index.
  • Use Write-Host to print the random string on the PowerShell console.

First, we used the ToCharArray() method to create an array of characters stored in the $charArray variable. After that, we used the New-Object cmdlet to create an instance of the System.Random class and stored it in the $randomObject variable; we instantiated the System.Random class to create random indexes. We will see it later in the for loop.

Next, we declared and initialized the $randomString variable with an empty string. After that, we used the for loop to make 10 iterations; for each iteration, we used the Next() method to create a random index and stored it in the $randomIndex variable. Note that the random index will always be in the range of 0 to array's length.

We used this $randomIndex to retrieve a character from $charArray and saved it in the $randomCharacter variable. Further, we used the concatenation operator represented with += to concatenate the current $randomCharacter with $randomString. Finally, we printed the value of the $randomString variable on the PowerShell console using the Write-Host cmdlet.

Following is an alternative approach to the above solution. We used the ForEach loop for iterations, and it contains comparatively fewer lines of code.

Using System.Web module

Use the GeneratePassword() method from System.Web module to produce a random string in PowerShell.

For this solution, we have to load System.Web into PowerShell using LoadWithPartialName() method of Reflection.Assembly class. After importing it, we used the GeneratePassword() method of the Membership class, which resides in the System.Web.Security namespace.

The GeneratePassword() method took two arguments; first was the password’s length, and second, was its complexity. In our case, we got the password of length 20 characters with 2 complexity representing the 2 non-alphanumeric characters in addition to numbers and letters. On successful execution of the above script, we will get a random password string you can see above.

Using Get-Random Cmdlet with -join Operator

Use the Get-Random cmdlet with the -join operator to generate a random string comprising of lowercase letters and numbers in PowerShell.

Before understanding what the above command does, let’s break it down into chunks and learn. The (48..57) + (97..122) create an array of Unicode values denoting the characters’ ASCII codes between a-z (97-122) and 0-9 (48-57). This array was piped with the Get-Random cmdlet, which selected random 10 values because we specified the count of 10 using -Count.

Now, the chosen 10 random characters were passed to the next process % {[char]$_}, which piped them to the ForEach-Object cmdlet and converted every Unicode value to its corresponding character. Finally, we used the -join operator to join all the characters. So, the above command will generate and join 10 random characters where each character will be a lowercase letter or number. Alternatively, we can use the following command to have uppercase letters and special characters.

Use the Get-Random cmdlet with the -join operator to generate a random string containing lowercase letters, uppercase letters, numbers and special characters in PowerShell.

Until this point, we generated one random string; what if we are supposed to create an n number of random strings in PowerShell?

Using for Loop with get-random to Create n Random Strings

Use the for loop with get-random to generate an n number of random strings in PowerShell.

This example is similar to previous ones but generates 5 random alphanumeric strings. How? We used the for loop to perform 5 iterations, one iteration for every random string. In each iteration, we created an array of alphanumeric characters via concatenating numbers, lowercase letters, and uppercase letters, which were randomly sorted.

The [0..9] selected the first 10 characters from the randomized string and joined them using the -join operator. This process was repeated for all 5 strings.

That’s all about how to generate random String in PowerShell.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *