PowerShell CheatSheet – Maths!

PowerShell loves maths!
By using System.Math .NET Framework class, PowerShell is a great calculator.
Here are common examples of System.Math functions

  1. Returning the absolute value of a Decimal number
  2. [int]$x=-19.69
  3. Returning the smallest integral value that is greater than or equal to the specified decimal number
  4. [int]$x=-19.69
  5. Returning the largest integer less than or equal to the specified decimal number
  6. [int]$x=-19.69
  7. Returning the larger of two decimal numbers
  8. [int]$x=9
  9. Returning the smaller of two decimal numbers
  10. [int]$x=9
  11. Returning a specified number raised to the specified power
  12. [int]$x=9
  13. Returning a decimal value to the nearest integral value
  14. [int]$x=9.9548
  15. Returning the square root of a specified number
  16. [int]$x=81
  17. Calculating the integral part of a specified decimal number
  18. [int]$x=56648.4665
  19. Calculating the area of a circle (or anything Pi’s related…)
  20. [decimal]$Pi=[System.Math]::Pi
    $area=([System.Math]::Pow($radius,2)) * $Pi

Of course, for sysadmins, the most used function will be to convert values from bytes to Kb, Mb, Gb, etc. PowerShell knows about it:

PS Fab:\> 1KB
PS Fab:\> 1MB
PS Fab:\> 1GB
PS Fab:\> 1TB
PS Fab:\> 1PB

It’s probably in server inventory, dealing with disk spaces, that you will use those most:

$disk=Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='C:'" | Select-Object $_.Size
Write-Host "Disk C total capacity (in bytes) => $By bytes"
Write-Host "Disk C total capacity (converted in Gb) => $Gb Gb"

Finally, since PowerShell is able do mathematical operations, we can obviously use the main operators on numbers, but on strings too:

The Addition operator (+)Adds two values together1 + 1
$y=” string”
$z=$x + $y
another string
The Subtraction operator (-)Substracts one value from another1 – 1
$i- –
$x=”another string”
$y=”another “
$z=$x -replace $y, “” #(Yes, I’m a cheater!)
The Multiplication operator (*)Multiplies two values together2 * 2
$x * 2
The Division operator (/)Divides two values10 / 2
28 / 5
The Modulus operator (%)Returnq the remainder from a division operation25 % 5
28 % 5
0 #(Of course!)

Leave a Reply to bteskepu Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top