Techibee.com

PowerShell: Get random elements from an array

In this post, we will see how to use Get-Random cmdlet to get random elements or items from a list(aka array) in PowerShell. Along with that we will also see other use cases of Get-Random and find out where else we can use it.

This cmdlet is available in previous versions of PowerShell, so there is no specific version requirement for this. For the ease of demonstration, I will use an array of numbers from 1 to 10 and use Get-Random cmdlet to display a random number out of it.

@(1,2,3,4,5,6,7,8,9,10) | Get-Random

In the above example, the list can be anything. I mean it can be a list of strings, numbers or any other items. Look at the below example to understand it better.

$services = Get-Service
$services | Get-Random

This will display a service randomly from the array of service objects. So, it is very clear that the input list can be an array of any kind of object. For the sake of further exploration, I will limit this to numbers only as some of the arguments works with numbers only.

Let us say if you need to get a random number below 100 in your scripts, do you need to generate an array first that contains numbers from 1 to 100 first? No, you don’t need to do that. You can use -Maximum parameter for this purpose.

Get-Random -Maximum 100

You can use -Minimum Parameter to specify if your range doesn’t start from 1. The below command generates a random number between 50 and 100.

Get-Random -Minimum 50 -Maximum 100

What if I am no longer interested in generating a single random number but I need 3 random numbers from the given range. The -Count parameter is very helpful in such scenarios.

1..100 | Get-Random -Count 3

The above command displays 3 random numbers between 1 and 100. However, there is a limitation here. You can not use -Maximum & -Minimum parameters with -Count parameter. I wonder why Microsoft placed such limitation. Anyways, it is the way it is.

So far we have seen several ways you can use Get-Random cmdlet for random numbers generation. Before I conclude, I want to share another tip that helps you to display all elements in array but with their order changed. This is useful if you want to shuffle the items in an array.

1..10 | Get-Random -Count 10

Have you noticed that the number we provided to the Count parameter is the size of the input? It can be size of the input array or more than that.

Hope this article is helpful. Let me know if you have any questions or more innovative ways of using Get-Random cmdlet.

Exit mobile version