考虑以下 Powershell 代码段:
[Uint64] $Memory = 1GB
[string] $MemoryFromString = "1GB"
[Uint64] $ConvertedMemory = [Convert]::ToUInt64($MemoryFromString)
第三行失败:
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
如果我检查
$Memory
的内容:PS C:\> $Memory
1073741824
很好
那么,如何在 Powershell 中将值“1GB”从字符串转换为 UInt64?
最佳答案
您的问题是ToUint64
无法理解Powershell语法。您可以通过执行以下操作来解决它:
($MemoryFromString / 1GB) * 1GB
因为
$MemoryFromString
将在除法之前转换其数值。这是有效的,因为在除法点 Powershell 尝试使用其规则将字符串转换为数字,而不是烘焙到
ToUInt64
中的 .Net 规则。作为转换的一部分,如果发现 GB
后缀并应用它的规则将 "1GB"
字符串扩展为 1073741824
编辑:或者正如 PetSerAl 指出的那样,你可以这样做:
($MemoryFromString / 1)
关于powershell - 如何从Powershell中的字符串转换为UInt64?字符串到数字的转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41088561/