PowerShell Pipeline

How To Do Math with PowerShell

PowerShell is more than just scripting and automation. Given the right functions, you can also use it to solve numerical equations -- from the simple to the complex. Here's how.

PowerShell is not just about writing scripts and working with various things such as Active Directory and SQL Server and the operating systems that these platforms ride on. While we can use it for fun things such as getting the weather and automating some aspect of our lives, PowerShell can also be a useful tool for such things as mathematics.

Through the use of functions, we can write tools to solve various formulas, given that the logic behind the function is sound. In this column, I will show you different ways we can use PowerShell to solve math problems, starting with some basic uses and then working up to writing a function which can be used to solve some math formulas.

First off, we will just run a couple of commands to show the simplicity of performing actions such as adding or subtracting numbers in the console. Adding is as simple as just typing out the numbers that you wish to add together. You can add as many numbers together that you want as long as you end the command with a number:

As you can see, PowerShell knows that we are looking to perform an arithmetic operation and proceeds to display the solution to the problem. In the case of not ending with a number, the console will treat it as a line continuation and wait for you to input a number, which will then present the solution to the problem.

This same process applies to subtraction, division and multiplication with their appropriate arithmetic operators:

Order of operations can be handled using parentheses to ensure that we are adding values first and then dividing the results to another number. Otherwise, the results could differ greatly:

Working with [Math]
The .NET [Math] type contains 28 methods and two constant properties that make performing more complex operations simpler by doing some of the hard work behind the scenes.

[Click on image for larger view.]

The two constants are for Pi and E. Pi can go up to 14 digits and E will also be displayed to 14 digits.

We can use the Sqrt method to find the square root of a given number pretty quickly, as shown below:

[math]::Sqrt(144)

Another common method that could be used is POW to raise a number by a given power. In this example, I will raise 2 by the power of 10 and see what the result is:

[math]::Pow(2,10)

Fun with Formulas
We can easily write out some formulas to solve problems and even make them into reusable functions to assist with future problems that we may need to solve later.

Finding the perimeter of a square is as simple as adding the four sides together to get the solution:

#Parameter of a Square
$Result = 5+5+5+5
[pscustomobject]@{
    Side1 = 5
    Side2 = 5
    Side3 = 5
    Side4 = 5
    Perimeter = $Result
}

I went overkill for this example, but I would rather display the object showing the sides along with the perimeter instead of just some console or text-only output of the result.

Another example to show off is to find the area of a rectangle instead. Instead of adding all of the sides, we will multiple the length and width of the rectangle to get the area:

#Area of a Rectangle
$Length = 10 
$Width = 5
$Result = $Length * $Width
[pscustomobject]@{
    Length = $Length
    Width = $Width
    Perimeter = $Result
}

We can package this into a function that will not only provide us the area of the rectangle, but also tell us either the length or width of the rectangle if we happen to provide the area along with the width or length:

Function Get-Rectangle {
    Param (
        [parameter()]
        [int]$Length,
        [parameter()]
        [int]$Width,
        [parameter()]
        [int]$Area
    )
    If ($PSBoundParameters.ContainsKey('Length') -AND $PSBoundParameters.ContainsKey('Width')) {
        $Area = $Width * $Length
    }
    ElseIf ($PSBoundParameters.ContainsKey('Area') -AND $PSBoundParameters.ContainsKey('Length')) {
        $Width = $Area / $Length
    }
    ElseIf ($PSBoundParameters.ContainsKey('Area') -AND $PSBoundParameters.ContainsKey('Width')) {
        $Length = $Area / $Width
    }
    Else {
        Break
    }

    [pscustomobject]@{
        Length = $Length
        Width = $Width
        Area = $Area
    }
}

Now we can use Get-Rectangle and supply it a couple of parameters to calculate either the area given the length and width, or the length with the area and width values.

Get-Rectangle -Length 10 -Width 5
Get-Rectangle -Width 5 -Area 50

Using PowerShell to work math problems and some complex equations can be done easily! For some formulas, you can write your own functions to handle all aspects of an equation. What I have covered just showed some of the most basic approaches to working with math in PowerShell, but you should definitely expand out and see what other uses you can come up with.

About the Author

Boe Prox is a Microsoft MVP in Windows PowerShell and a Senior Windows System Administrator. He has worked in the IT field since 2003, and he supports a variety of different platforms. He is a contributing author in PowerShell Deep Dives with chapters about WSUS and TCP communication. He is a moderator on the Hey, Scripting Guy! forum, and he has been a judge for the Scripting Games. He has presented talks on the topics of WSUS and PowerShell as well as runspaces to PowerShell user groups. He is an Honorary Scripting Guy, and he has submitted a number of posts as a to Microsoft's Hey, Scripting Guy! He also has a number of open source projects available on Codeplex and GitHub. His personal blog is at http://learn-powershell.net.

comments powered by Disqus
Most   Popular