Byte Conversion with PowerShell
Powershell includes numeric multipliers that allow users to use 1kb instead of 1024 and so on with megabytes, gigabytes, terabytes, and petabytes.
This is feature of PowerShell is commonly used with commands like Set-VMMemory:
Set-VMMemory -StartupBytes 4gb -MinimumBytes 2gb MyVirtualMachine
It also makes conversion a simple matter of division, multiplication and (optionally) typecasting:
Get-ChildItem -File |
Sort-Object Length |
Select-Object -Last 10 @{
Name='Size (MB)'
Expression={[long]($_.Length / 1mb)}
}, Name, Modified
That works, but I found it tedious to type and that it made my code less readable. So I wrote ByteCalculationFunctions.ps1 to make it easier to read and type commands that include byte conversion.
For example, to get an integer representation of the number of bytes in 9 gigabyte:
bytesfromgigs 9 # will return 9663676416
So, the expression above is (slightly) easier to write and read:
Get-ChildItem -File |
Sort-Object Length |
Select-Object -Last 10 @{
Name='Size (MB)'
Expression={bytestomegs $_.Length}
}, Name, Modified
Also, they take advantage of PowerShell Pipelines to make inline conversion easier and more readable:
1024 | bytestok # 1
260046848 | bytestomegs # 260046848
7 | bytesfromgigs | bytestomegs # 7168
259072 | bytesfrommegs | bytestogigs # 253
To use them, import them into your current PowerShell session:
Invoke-WebRequest https://mig.us/bcfps1 | Invoke-Expression
../