If you insist on working with a string and keeping with the -replace
operator, you can use the following:
[double]($size -replace "[^\d\.]+$")
If you maintain a numeric value type like int
or double
, you can use other means to work with your data. You can still output a string while keeping $size
a double.
$size = 23.9
$unit = 'GB'
"{0} {1}" -f $size,$unit
23.9 GB
A very similar concept as the above example would be to create $size
as a custom object.
$size = [pscustomobject]@{Size = 23.9; Unit = 'GB'}
"{0} {1}" -f $size.Size,$size.Unit
You can do dynamic unit assignment. If we assume you are starting with a size in bytes, you can assign the unit and do the conversion.
if ($size -ge 1GB)
{
$newSize = [pscustomobject]@{
Size = $size/1GB; Unit = 'GB'
}
}
elseif ($size -ge 1MB)
{
$newSize = [pscustomobject]@{
Size = $size/1MB; Unit = 'MB'
}
}
elseif ($size -ge 1KB)
{
$newSize = [pscustomobject]@{
Size = $size/1KB; Unit = 'KB'
}
}
else
{
$newSize = [pscustomobject]@{
Size = $size; Unit = 'B'
}
}