[int]$...">

In Powershell, what is the idiomatic way to convert a string to int?

The only method I found is direct listing:

> $numberAsString = "10" > [int]$numberAsString 10 

Is this a standard approach in Powershell? Is the test expected to be done earlier to ensure that the conversion is successful, and if so, how?

+42
powershell
Mar 14 '12 at 11:00
source share
7 answers

Using .net

 [int]$b = $null #used after as refence $b 0 [int32]::TryParse($a , [ref]$b ) # test if is possible to cast and put parsed value in reference variable True $b 10 $b.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 System.ValueType 

pay attention to this (force forced check function)

 $a = "10" $a + 1 #second value is evaluated as [string] 101 11 + $a # second value is evaluated as [int] 21 
+45
Mar 14 '12 at 11:13
source share

You can use the -as operator. If the prize returns, you will receive a number:

 $numberAsString -as [int] 
+52
Mar 14 2018-12-12T00:
source share

A quick true / false test of whether it will be passed in [int]

 [bool]($var -as [int] -is [int]) 
+11
Mar 14 '12 at 11:37
source share

For me, $numberAsString -as [int] of @Shay Levy is best practice, I also use [type]::Parse(...) or [type]::TryParse(...)

But depending on what you need, you can simply put a line containing the number to the right of the arithmetic operator with int to the left, the result will be Int32:

 PS > $b = "10" PS > $a = 0 + $b PS > $a.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 System.ValueType 

You can use Exception (try / parse) to behave in case of a problem

+8
Mar 14 '12 at 13:00
source share

I would probably do something like this:

 [int]::Parse("35") 

But I'm not a Powershell guy. It uses the static Parse method from System.Int32. It should throw an exception if the string cannot be parsed.

+3
Mar 14 '12 at 11:11
source share

Set the answer to Shavy Levy:

 [bool]($var -as [int]) 

Since $ null evaluates to false (in bool), this statement will give you true or false depending on whether the casting was successful.

+1
Mar 08 '16 at 13:47
source share
 $source = "number35" $number=$null $result = foreach ($_ in $source.ToCharArray()){$digit="0123456789".IndexOf($\_,0);if($digit -ne -1){$number +=$\_}}[int32]$number 

Just give it the numbers and it will convert to Int32

-one
Nov 21 '13 at 18:46
source share



All Articles