如何从Powershell中的字符串转换为UInt64?字符串到数字的转换 [英] How to convert to UInt64 from a string in Powershell? String-to-number conversion

查看:55
本文介绍了如何从Powershell中的字符串转换为UInt64?字符串到数字的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 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的内容:

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?字符串到数字的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆