Skip to content

Instantly share code, notes, and snippets.

@nikyodo85
Last active October 31, 2018 16:41
Show Gist options
  • Save nikyodo85/07f15bd89115a825e0395033e66ae934 to your computer and use it in GitHub Desktop.
Save nikyodo85/07f15bd89115a825e0395033e66ae934 to your computer and use it in GitHub Desktop.
Just a quick module with a function to parse size unit. For example: Parse-SizeUnit "1GB" or "1 GB" will return 1073741824. Improve support up to YottaByte.
function Parse-SizeUnit {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)][string]$SizeUnit
)
$SizeUnit = $SizeUnit.Trim()
$Size = 0;
$Unit = 'B';
if ($SizeUnit -match '\d+\s+\w*B$') {
$SizeUnitSplit = $SizeUnit -split '\s+'
$Size = [int]$SizeUnitSplit[0]
$Unit = $SizeUnitSplit[1]
} elseif ($SizeUnit -match '\d+\w*B$') {
$SizeUnit -match '\d+'
$Size = [int]$Matches[0]
$SizeUnit -match '\D+\w*B$'
$Unit = $Matches[0]
}
if ($Unit -eq 'YB') {
$Size * 1PB * 1GB
} elseif ($Unit -eq 'ZB') {
$Size * 1PB * 1MB
} elseif ($Unit -eq 'EB') {
$Size * 1PB * 1KB
} elseif ($Unit -eq 'PB') {
$Size * 1PB
} elseif ($Unit -eq 'TB') {
$Size * 1TB
} elseif ($Unit -eq 'GB') {
$Size * 1GB
} elseif ($Unit -eq 'MB') {
$Size * 1MB
} elseif ($Unit -eq 'KB') {
$Size * 1KB
} elseif ($Unit -eq 'B') {
$Size
} else { 0 }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment