O'Reilly logo

Windows PowerShell Cookbook, 3rd Edition by Lee Holmes

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Calculations and Math

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 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, 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.

Perform Simple Arithmetic

Problem

You want to use PowerShell to calculate simple mathematical results.

Solution

Use PowerShell’s arithmetic operators:

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus

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

Assignment variations of the previously listed operators

()

Precedence/order of operations

For a detailed description of these mathematical operators, see Simple Operators.

Discussion

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;
result = 3/2;

This is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required