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

Question:

Consider the following Powershell snippet:

The 3rd Line fails with:

If I check the contents of $Memory:

That works fine.

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

Answer:

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

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:

Source:

How to convert to UInt64 from a string in Powershell? String-to-number conversion by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply