Search code examples
powershelltype-conversionpowershell-5.0

How to convert to UInt64 from a string in Powershell? String-to-number conversion


Consider the following Powershell snippet:

[Uint64] $Memory = 1GB
[string] $MemoryFromString = "1GB"
[Uint64] $ConvertedMemory = [Convert]::ToUInt64($MemoryFromString)

The 3rd Line fails with:

Exception calling "ToUInt64" with "1" argument(s): "Input string was not in a correct format."
At line:1 char:1
+ [Uint64]$ConvertedMemory = [Convert]::ToUInt64($MemoryFromString)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

If I check the contents of $Memory:

PS C:\> $Memory
1073741824

That works fine.

So, how do I convert the value "1GB" from a string to a UInt64 in Powershell?


Solution

  • Your problem is that the ToUint64 doesn't understand the Powershell syntax. You could get around it by doing:

    ($MemoryFromString / 1GB) * 1GB
    

    As the $MemoryFromString will be converted its numeric value before the division.

    This works because at the point of division Powershell attempts to convert the string to a number using its rules, rather than the .Net rules that are baked into ToUInt64. As part of the conversion if spots the GB suffix and applies it rules to expand the "1GB" string to 1073741824

    EDIT: Or as PetSerAl pointed out, you can just do:

    ($MemoryFromString / 1)