Share via


PowerShell Tricks: Get Random Numbers and Sum up the Values

PowerShell Tricks


Recently saw a request to sum random numbers if it is greater than 9. There are many ways to do this using String Manipulation, Regular Expression, etc.

Requirement:

  1. Generate a random number
  2. If the number is greater than 9 sum the values
  3. E.g.: if output of Get-Random return 22 it should return 2+2 = 4

PowerShell Way of Doing!!!




$number = 1..50 | Get-Random
Write-Host "The Value is" $number -ForegroundColor Green
if($number -gt 9){$number -split "" | Measure-Object -Sum}
else{Write-Host "Not Applicable for addition process" -ForegroundColor Green}

The trick is to use the -split and Measure-Object

Output
The value is 50
Sum: 5

The Value is 50
 
Count    : 4
Average  : 
Sum      : 5
Maximum  : 
Minimum  : 
Property :

For testing we used 1..50

Power of Shell!!! This trick may help few for their custom processing.