Review of PowerShell Maths

Windows PowerShell Maths

PowerShell is very good at understand whether a command in your script should be handled as text or as a number.  Incidentally, the more you study PowerShell’s different math techniques, the more reasons you will find to turn to PowerShell rather than VBScript or Excel.

Topics for PowerShell Maths

For once, I favour the English word maths (plural) because we are dealing with numerous aspects of math calculation.

  1. Simple Arithmetic Operations in PowerShell
  2. PowerShell [Math]::Static Methods
  3. Measure-Object Cmdlet
  4. Get-Date Cmdlet
  5. PowerShell’s Concatenator (+)
  6. PowerShell ‘=’ Sign and -eq Operator
  7. Counters for Loops $i++

 ♣

Review of Basic PowerShell Mathematics

Get started by simply typing numbers at the PowerShell command line.  You can use the 4 well-known operators + – * (asterisk) and / (forward slash), try these calculations:

68 + 47
365 -127
38 * 15
22 / 7

Simple Arithmetic Operations in PowerShell

PowerShell handles basic maths calculations, such as add and multiply with deceptive ease. Try these simple arithmetic computations:

Clear-Host
$1stNum = 22
$2ndNum = 7
Write-Host "Add, Subtract, Multiply and Divide"
Write-Host "———————————–"
$1stNum + $2ndNum    #Add ………. Answer 29
$1stNum $2ndNum     #Subtract … Answer 15
$1stNum * $2ndNum     #Multiply …. Answer 154
$1stNum / $2ndNum     #Divide ……. Answer 3.14285 (pi)

Putting PowerShell Maths to Work

Suppose you want to test a router connection.  We could use ping, but I have chosen Win32_PingStatus.  The point is that Microsoft has designed PowerShell so that it can deal with adding 1 to 192.168.1.1.

# PowerShell Ping math script
$i =1
$IPAddress = "192.168.1."
Do { $Ip4th = $IPAddress+ $i
$PingMath = Get-WmiObject Win32_PingStatus -f "Address='$Ip4th'"
$PingMath | Format-Table Address, StatusCode -hideTableHeaders -auto; $i++
}
Until ($i -eq 20)

Note 1: A StatusCode of 0 means a successful ping; 11003 is the equivalent of 'Destination host unreachable'.

Guy Recommends: Free WMI Monitor for PowerShellSolarwinds Free WMI Monitor for PowerShell

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try – it’s free.

Download your free copy of WMI Monitor

Review of PowerShell [Math]::Static Methods

Thanks to PowerShell accessing .Net Framework, we can perform trickier math operations; observe the static syntax, [Math]::function().  The key point here is we are asking PowerShell to employ functions such as you would use in Excel.

Clear-Host
$1stNum = 22
$2ndNum = 7
Write-Host "[Math]::Round, Truncate and [int]"
Write-Host "———————————–"
[Math]::Round($1stNum / $2ndNum,2)
[Math]::Truncate($1stNum / $2ndNum)
[int]($1stNum / $2ndNum)

Note 2: Strictly speaking we should use [System.Math], however, the shorter [Math] works just fine.  See more on PowerShell’s static math functions.

Putting PowerShell Maths to Work

In this scenario we are investigating why a disk labelled 1 terabyte was actually only 931 gigabytes.

# PowerShell WMI class to get disk information
$Disk = Get-WmiObject Win32_diskdrive
Foreach ($Item in $Disk){
"{0,-28} {1,-20} " -f `
$Item.Name, $Item.Size}

Result: 1000202273280 (Bytes)

Let us employ PowerShell’s [Math]::Round static method to crack the problem.  Also observe where we divide by GB (gigabyte)

$Disk = Get-WmiObject Win32_diskdrive
Foreach ($Item in $Disk){
"{0,-28} {1,-20} " -f `
$Item.Name, ([Math]::Round($Item.Size/1GB,2))}

Result: 931.51 GB (GigaBytes)

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

PowerShell’s Concatenator (+)

Joining text strings in PowerShell is very easy, just call for the plus sign; you can even combine text strings with numbers.  Observe how seamlessly the simple plus (+) sign joins text, numbers and the result of calculations.

The only danger is overthink, looking for extra syntax when all you need is (+)

Clear-Host
"Guy " + "Thomas is over " + (100-40)

A more likely scenario would be combining fields, for example concatenating values stored in variables.

Clear-Host
$FirstName = "Guy "
$Surname = "Thomas "
$Age = 64
$FirstName + $Surname + $Age

My next example is more interesting because it uses [System.Datetime] and also the static function [Math]::Truncate.

Clear-Host
$FirstName = "Guy "
$Surname = "Thomas "
$Age = (Get-date) – ([System.Datetime]"24 June 1949")
$FirstName + $Surname + [Math]::Truncate($Age.Days/365)

Note 3: Trace the $Age variable; once again you can append a number to a text string.

Engineer's Toolset v10Guy Recommends: SolarWinds Engineer’s Toolset v10

This Engineer’s Toolset v10 provides a comprehensive console of 50 utilities for troubleshooting computer problems.  Guy says it helps me monitor what’s occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it’s like having free rein of a sweetshop.  Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools.  Try the SolarWinds Engineer’s Toolset now!

Download your fully functional trial copy of the Engineer’s Toolset v10

PowerShell -eq and ‘=’ Sign

For a purely mathematical calculation PowerShell uses the -eq conditional operator. The only place beginners see the equals sign in PowerShell is when assigning variables.

The -eq operator has a whole family of relatives, such as -ne (not equal), and then also the branch of the family containing greater than and less than, (-gt and -lt).

Mission: To Find Zero Length Files
Key command: Where-Object {$_.length -eq 0}

# PowerShell script to find zero length files in Windows folder
Clear-Host
$FileSource = "C:\Windows"
$Empty = Get-ChildItem -path $Filesource -Recurse -ErrorAction SilentlyContinue
$Empty | Where-Object {$_.Length -eq 0} | Ft FullName, Length -AutoSize

Note 4: Observe the use of ‘=’ to declare variables; but -eq for the actual comparison operator.

See much more on PowerShell’s comparison operators »

Summary:  Review of Windows PowerShell Maths

PowerShell always makes an effort to understand whether your code is text or a number.  The secret of handling more complex maths functions is to understand [System.Math]:: static functions.

If you like this page then please share it with your friends

 


See more PowerShell examples of math operations

PowerShell Maths Index   • Windows PowerShell   • PowerShell Splatting

PowerShell Math  • Comparison Operators   • PowerShell Measure Object   • Measure Command

PowerShell Tutorials  • Syntax  • Pipeline  • PowrShell Quotes  • Free WMI Monitor

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.