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
    [System.Math]::Abs($x)
    
  3. Returning the smallest integral value that is greater than or equal to the specified decimal number
  4. [int]$x=-19.69
    [System.Math]::Ceiling($x)
    
  5. Returning the largest integer less than or equal to the specified decimal number
  6. [int]$x=-19.69
    [System.Math]::Floor($x)
    
  7. Returning the larger of two decimal numbers
  8. [int]$x=9
    [int]$y=42
    [System.Math]::Max($x,$y)
    
  9. Returning the smaller of two decimal numbers
  10. [int]$x=9
    [int]$y=42
    [System.Math]::Min($x,$y)
    
  11. Returning a specified number raised to the specified power
  12. [int]$x=9
    [System.Math]::Pow($x,2)
    
  13. Returning a decimal value to the nearest integral value
  14. [int]$x=9.9548
    [System.Math]::Round($x,2)
    
  15. Returning the square root of a specified number
  16. [int]$x=81
    [System.Math]::Sqrt($x)
    
  17. Calculating the integral part of a specified decimal number
  18. [int]$x=56648.4665
    [System.Math]::Truncate($x)
    
  19. Calculating the area of a circle (or anything Pi’s related…)
  20. [decimal]$Pi=[System.Math]::Pi
    [int]$radius=10
    $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
1024
PS Fab:\> 1MB
1048576
PS Fab:\> 1GB
1073741824
PS Fab:\> 1TB
1099511627776
PS Fab:\> 1PB
1125899906842624

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
$By=($disk.Size)
Write-Host "Disk C total capacity (in bytes) => $By bytes"
$Gb=[System.Math]::Round(($disk.Size)/1GB,2)
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:

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

Leave a Reply

Scroll to Top