Prof. Powershell

Easy as PI

Math class is in session with these Powershell tricks.

PowerShell supports all the traditional math operators like * / and +. But suppose you need more advanced calculations. Because PowerShell is built on the .NET Framework, you can access the .NET classes directly and for this lesson that will be the System.Math class. This class doesn't have a constructor so you don't use New-Object. Instead access the object directly.

First, the object has fields for the constants pi and e:

PS C:\> [math]::e
2.71828182845905
PS C:\> [math]::pi
3.14159265358979

Sure you could create a variable for pi using 3.14, but this is more fun:

PS C:\> $r=2.3456
PS C:\> [math]::pi*($r*$r)
17.2845381146072

The [Math] class contains all of your familiar trigonometry functions like sin, cos and tan. Although I don't do much trig these days and probably not in PowerShell. But you may find these methods useful.

Return an absolute value:

PS C:\> [math]::abs(-4)
4

Return a square root:

PS C:\> [math]::sqrt(64)
8

Return one number raised to another number such as 2 to the 8th power:

PS C:\> [math]::pow(2,8)
256

Using this method I could rewrite my first example:

PS C:\> [math]::pi*[math]::pow($r,2)
17.2845381146072

But I find it just as easy to write ($r*$r).

One math related task you are likely to use are random numbers, perhaps as part of a password generating routine or maybe even an office lottery. To get random numbers use the System.Random class. You'll find it easier to create an object using the New-Object cmdlet:

PS C:\> $random=new-object system.random

You can either generate a random number that is less than a given value using the Next() method:

PS C:\> $random.next(10)
2

This value will always be positive. Or return a value within a given range by specifying a lower and upper limit:

PS C:\> $random.next(1024,2048)
1873

You can learn more about the math class by reviewing the MSDN documentation.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular

Upcoming Training Events

0 AM
Live! 360 Orlando
November 17-22, 2024
TechMentor @ Microsoft HQ
August 11-15, 2025