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?
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 You can use the -as operator. If the prize returns, you will receive a number:
$numberAsString -as [int] A quick true / false test of whether it will be passed in [int]
[bool]($var -as [int] -is [int]) 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
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.
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.
$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