Quick article today. Microsoft designed PowerShell to make it easy to work with quantities of kilobytes, megabytes, gigabytes, terabytes, and petabytes using a type suffix:
PowerShell 7.2.2 Copyright (c) Microsoft Corporation. https://aka.ms/powershell Type 'help' to get help. PS /home/sec504> $size = 1KB PS /home/sec504> $size 1024
When you specify a number (an integer or a floating point value) with the suffix of KB, MB, GB, TB, or PB, PowerShell will represent that as a quantity of bytes (where there are 1024 bytes in 1KB). This is really helpful when dealing with file sizes, estimating download times, and other operations dealing with quantities of bytes!
You can use uppercase or lowercase letters for the type suffix, but PowerShell does not distinguish between bytes and bits using an uppercase B or a lowercase b; PowerShell treats both as a number of bytes. I'll use uppercase letters to avoid confusion.
How many bytes is a 530MB file?
PS /home/sec504> 530MB 555745280
How long will it take to download a 42GB file at 2MB/sec?
PS /home/sec504> 42GB/2MB 21504 # In seconds PS /home/sec504> (42GB/2MB)/60 358.4 # In minutes PS /home/sec504> (42GB/2MB)/(60*60) 5.97333333333333 # In hours
How many MB is a file that is 1073741824 bytes?
If you want convert a value to a different unit of bytes, divide by 1:
PS /home/sec504> 1073741824/1MB 1024
How many GB of storage do I need to save 60 video files that are around 350MB each?
PS /home/sec504> (350MB * 60)/1GB 20.5078125
Choose the number of decimal places by placing the operation in parenthesis and calling the .ToString() method:
PS /home/sec504> ((350MB * 60)/1GB).ToString(".##") 20.51
How many MB is the specified packet capture file? How many GB?
If you are working with a file item, you can access the Size property:
PS /home/sec504> $incidentpcap = Get-ChildItem ./labs/falsimentis/falsimentis.pcap PS /home/sec504> $incidentpcap.Size/1MB 3663.77952289581 PS /home/sec504> ($incidentpcap.Size/1MB).ToString(".##") 3663.78 PS /home/sec504> $incidentpcap.Size/1GB 3.57790969032794 PS /home/sec504> ($incidentpcap.Size/1GB).ToString(".##") 3.58
I have a 1.2PB disk image. If I split it into equal chunks, how many 128TB drives do I need to copy the data?
PS /home/sec504> [Math]::Ceiling(1.2PB/128TB) 10
Here I'm using the .NET Math class to call the Ceiling() static method to always round up the quotient.
PowerShell's type suffix for quantities of bytes is a handy feature; be sure to take advantage of it anytime you work with file sizes, download speeds, and other administration tasks!
-Joshua Wright
Return to Getting Started With PowerShell
Joshua Wright is the author of SANS SEC504: Hacker Tools, Techniques, and Incident Handling, a faculty fellow for the SANS Institute, and a senior technical director at Counter Hack.