问题描述
考虑以下 Powershell 代码段:
Consider the following Powershell snippet:
[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
的内容:
If I check the contents of $Memory
:
PS C:> $Memory
1073741824
效果很好.
那么,如何在 Powershell 中将值1GB"从字符串转换为 UInt64?
So, how do I convert the value "1GB" from a string to a UInt64 in Powershell?
推荐答案
您的问题是 ToUint64
不理解 Powershell 语法.您可以通过以下方式解决它:
Your problem is that the ToUint64
doesn't understand the Powershell syntax. You could get around it by doing:
($MemoryFromString / 1GB) * 1GB
因为$MemoryFromString
会在除法前转换成它的数值.
As the $MemoryFromString
will be converted its numeric value before the division.
这是有效的,因为在除法点,Powershell 会尝试使用其规则将字符串转换为数字,而不是使用 ToUInt64
中的 .Net 规则.作为转换的一部分,如果发现 GB
后缀并应用它的规则将 "1GB"
字符串扩展为 1073741824
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
或者正如 PetSerAl 指出的那样,您可以这样做:
Or as PetSerAl pointed out, you can just do:
($MemoryFromString / 1)
这篇关于如何从 Powershell 中的字符串转换为 UInt64?字符串到数字的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!