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

前端 未结 2 862
抹茶落季
抹茶落季 2021-01-14 02:12

Consider the following Powershell snippet:

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


        
2条回答
  •  一整个雨季
    2021-01-14 02:32

    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)
    

提交回复
热议问题