Question:
Consider the following Powershell snippet:
1 2 3 4 |
[Uint64] $Memory = 1GB [string] $MemoryFromString = "1GB" [Uint64] $ConvertedMemory = [Convert]::ToUInt64($MemoryFromString) |
The 3rd Line fails with:
1 2 3 4 5 6 7 |
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
:
1 2 3 |
PS C:\> $Memory 1073741824 |
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:
1 2 |
($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:
1 2 |
($MemoryFromString / 1) |