Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: convert string to number

Ok, I am beginner - and lost with this:

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

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

The Array has these values (2 drives):

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

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:

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

For help many thanks in advance.

like image 259
MMAX Avatar asked Aug 15 '14 07:08

MMAX


People also ask

How do I convert string to decimal in PowerShell?

[decimal]$string. Replace(",", ".")

What does $_ in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.


1 Answers

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).

Give this method a try:

[string]$strNum = "1.500" [int]$intNum = [convert]::ToInt32($strNum, 10)  $intNum 
like image 198
Roderick Bant Avatar answered Oct 02 '22 20:10

Roderick Bant