Powershell:将字符串转换为数字 [英] Powershell: convert string to number

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

问题描述

好吧,我是初学者 - 迷失了这个:

Ok, I am beginner - and lost with this:

我有一个阵列,其中捕获了来自 WMI 的一些驱动器数据:

I have an Array where some drive data from WMI are captured:

$drivedata = $Drives | select  @{Name="Kapazität(GB)";Expression={$_.Kapazität}}

阵列具有以下值(2 个驱动器):

The Array has these values (2 drives):

@{Kapazität(GB)=1.500} @{Kapazität(GB)=1.500}

只想将 1.500 转换为数字 1500

and just want to convert the 1.500 into a number 1500

我尝试了在这里找到的不同建议,但无法使其正常工作:

I tried different suggestions I found here, but couldn't get it working:

-替换 ".","" 和 [int] 不起作用.我不确定正则表达式是否正确以及如何执行此操作.

-Replace ".","" and [int] doesn't work. I am not sure if regex would be correct and how to do this.

非常感谢您的帮助.

推荐答案

简单地将字符串转换为 int 不会可靠地工作.您需要将其转换为 int32.为此,您可以使用 .NET convert 类及其 ToInt32 方法.该方法需要一个 string ($strNum) 作为主要输入,以及 base number (10) 作为主要输入要转换到的数字系统.这是因为您不仅可以转换为十进制系统(10 基数),还可以转换为例如二进制系统(基数 2).

Simply casting the string as an int won't work reliably. You need to convert it to an int32. For this you can use the .NET convert class and its ToInt32 method. The method requires a string ($strNum) as the main input, and the base number (10) for the number system to convert to. This is because you can not only convert to the decimal system (the 10 base number), but also to, for example, the binary system (base 2).

试试这个方法:

[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)

$intNum

这篇关于Powershell:将字符串转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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