Easy as PI
Math class is in session with these Powershell tricks.
- By Jeffery Hicks
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
PS C:\> [math]::pi
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)
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)
Return a square root:
PS C:\> [math]::sqrt(64)
Return one number raised to another number such as 2 to the 8th power:
PS C:\> [math]::pow(2,8)
Using this method I could rewrite my first example:
PS C:\> [math]::pi*[math]::pow($r,2)
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)
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)
You can learn more about the math class by reviewing the MSDN documentation.
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.