Chapter 6. Calculations and Math

6.0. Introduction

Math is an important feature in any scripting language. Math support in a language includes addition, subtraction, multiplication, and division of course, but extends further into more advanced mathematical operations. So, it should not surprise you that PowerShell provides a strong suite of mathematical and calculation-oriented features.

Since PowerShell provides full access to its scripting language from the command line, though, this keeps a powerful and useful command-line calculator always at your fingertips!

In addition to its support for traditional mathematical operations, PowerShell also caters to system administrators by working natively with concepts such as megabytes and gigabytes, simple statistics (such as sum and average), and conversions between bases.

6.1. Perform Simple Arithmetic


You want to use PowerShell to calculate simple mathematical results.


Use PowerShell’s arithmetic operators:











+=, -=, *=, /=, and %=

Assignment variations of the above

( )

Precedence/Order of operations

For a detailed description of these mathematical operators, see “Simple Operators” in Appendix A.


One difficulty in many programming languages comes from the way that they handle data in variables. For example, this C# snippet stores the value of “1” in the result variable, when the user probably wanted the result to hold the floating point value of 1.5:

 double result = 0; ...

Get Windows PowerShell Cookbook now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.