Table of Contents
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 theGUID
(created in the previous step) to String format. - Use the
Write-Host
cmdlet to print the random string.
1 2 3 4 |
$randomString = ([System.Guid]::NewGuid()).ToString() Write-Host $randomString |
1 2 3 |
95ffbbf8-f721-4cf2-886d-dcdbfae00665 |
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 .NETRNGCryptoServiceProvider
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.
1 2 3 4 5 6 7 |
$randomBytesArray = New-Object byte[] 32 $rngObject = New-Object System.Security.Cryptography.RNGCryptoServiceProvider $rngObject.GetBytes($randomBytesArray) $randomString = [System.Convert]::ToBase64String($randomBytesArray) Write-Host $randomString |
1 2 3 |
6nh6ArzjvQSh6dW7DQ2C/3sTCZiKWpq/THDOTKHwg8E= |
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 theSystem.Random
class. - Use the
for
loop to perform the same jobs10
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.
- Create a random index using the
- Use
Write-Host
to print the random string on the PowerShell console.
1 2 3 4 5 6 7 8 9 10 11 |
$charsArray = "abcdefghijkmnopqrstuvwxyzABCEFGHJKLMNPQRSTUVWXYZ0123456789!"#$%&''()*+,-./:;<=>?@[\]^_`{|}~".ToCharArray() $randomObject = New-Object System.Random $randomString = "" for ($i = 0; $i -lt 10; $i++) { $randomIndex = $randomObject.Next(0, $charsArray.Length) $randomCharacter = $charsArray[$randomIndex] $randomString += $randomCharacter } Write-Host $randomString |
1 2 3 |
mQ7NgZmX!0 |
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.
1 2 3 4 5 6 |
$randomObject = New-Object System.Random $randomString="" 1..10 | ForEach { $randomString = $randomString + [char]$randomObject.Next(33,126) } Write-Host $randomString |
1 2 3 |
b?YDha&3>, |
Using System.Web
module
Use the GeneratePassword()
method from System.Web module to produce a random string in PowerShell.
1 2 3 4 |
[Reflection.Assembly]::LoadWithPartialName("System.Web") [System.Web.Security.Membership]::GeneratePassword(20,2) |
1 2 3 |
C&h%qk+Cxra7%s9=ZTq@ |
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.
1 2 3 |
-join ((48..57) + (97..122) | Get-Random -Count 10 | % {[char]$_}) |
1 2 3 |
m8w6dqfn5t |
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.
1 2 3 |
-join ((33..126) | Get-Random -Count 10 | % {[char]$_}) |
1 2 3 |
)H2T\n#,|v |
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.
1 2 3 4 5 |
for($i=0; $i -lt 5; $i++){ ([char[]]([char]'a'..[char]'z' + [char]'A'..[char]'Z') + 0..9 | sort {get-random})[0..9] -join '' } |
1 2 3 4 5 6 7 |
M5tV34J81u 2ErYS5uly6 jZ3ufpCBeh qBdsjZi1Cp CO2Ez3iDWY |
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.