Sometimes we need to work with file sizes in Powershell and a lot of those are displayed or required in bytes. I don’t know how good your skills are in calculating, in your head, to and from bytes, but mine ar not that great.
Let’s do a quick recap in what is what:
Name | Value | Value in Bytes |
B (Byte) | 1 Byte | 1 |
KB (KiloByte) | 1024 Bytes | 1024 |
MB (MegaByte) | 1024 KiloBytes | 1048576 |
GB (GigaBytes) | 1024 MegaBytes | 1073741824 |
TB (TerraByte) | 1024 GigaBytes | 1099511627776 |
So if we want to do e.g. 15 GB in bytes we need to lookup the value of GB in bytes and multiply it with 15 or do 15 * 1024 * 1024 *1024. I used to do this like this but found it very hard, mostly because I needed (or just wanted) to make certain that the calculation I did was correct. Then I found a much easier method to do so.
In Powershell we can use the use the following values instead of a byte value:
1kb ## 1024
1mb ## 1048576
1gb ## 1073741824
1tb ## 1099511627776
That’s way nicer already, but there is more. instead of using e.g. 1gb we can also enter e.g. 15gb and get in one easy entry the byte value.
15gb ## 16106127360
Okay now we have a way to easily go from GB to bytes, for example, but can we also easily go from bytes to GB? Yes we can.
16106127360/1gb ## 15
16106127360/1mb ## 15360
But what do we do when we have MB’s and what to transform it to e.g. Terrabytes?
(122880*1mb)/1tb ## 0,1171875
And one last quick tip. You can quickly round numbers by using the following method.
## Round by x decimals places
[math]::Round(0.1171875,2) ## 0,12
## By default it will round by 0 decimal places
[math]::Round(11.712) ## 12
Leave a Reply