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
- Returning the absolute value of a Decimal number
- Returning the smallest integral value that is greater than or equal to the specified decimal number
- Returning the largest integer less than or equal to the specified decimal number
- Returning the larger of two decimal numbers
- Returning the smaller of two decimal numbers
- Returning a specified number raised to the specified power
- Returning a decimal value to the nearest integral value
- Returning the square root of a specified number
- Calculating the integral part of a specified decimal number
- Calculating the area of a circle (or anything Pi’s related…)
[int]$x=-19.69 [System.Math]::Abs($x)
[int]$x=-19.69 [System.Math]::Ceiling($x)
[int]$x=-19.69 [System.Math]::Floor($x)
[int]$x=9 [int]$y=42 [System.Math]::Max($x,$y)
[int]$x=9 [int]$y=42 [System.Math]::Min($x,$y)
[int]$x=9 [System.Math]::Pow($x,2)
[int]$x=9.9548 [System.Math]::Round($x,2)
[int]$x=81 [System.Math]::Sqrt($x)
[int]$x=56648.4665 [System.Math]::Truncate($x)
[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:
Operator | Explanation | Example | Result |
---|---|---|---|
The Addition operator (+) | Adds two values together | 1 + 1 ——————– $i=1 $i++ ——————– $x=”another” $y=” string” $z=$x + $y | 2 ——————– 2 ——————– another string |
The Subtraction operator (-) | Substracts one value from another | 1 – 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 together | 2 * 2 ——————– $x=”string” $x * 2 | 4 ——————– stringstring |
The Division operator (/) | Divides two values | 10 / 2 28 / 5 | 5 5,6 |
The Modulus operator (%) | Returnq the remainder from a division operation | 25 % 5 28 % 5 | 0 #(Of course!) 3 |