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
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 a Microsoft MVP in Windows PowerShell, Microsoft Certified Trainer and an IT veteran with over 20 years of experience, much of it spent as an IT consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He works today as an independent author, trainer and consultant. Jeff writes the popular Prof. PowerShell column for MPCMag.com and is a regular contributor to the Petri IT Knowledgebase and 4SysOps. If he isn't writing, then he's most likely recording training videos for companies like TrainSignal or hanging out in the forums at PowerShell.org.
Jeff's latest books are Learn PowerShell 3 in a Month of Lunches, Learn PowerShell Toolmaking in a Month of Lunches and PowerShell in Depth: An Administrators Guide.
You can keep up with Jeff at his blog http://jdhitsolutions.com/blog, on Twitter at twitter.com/jeffhicks and on Google Plus (http:/gplus.to/JeffHicks)