In Powershell what is the idiomatic way of converting a string to an int?
You can use the -as operator. If casting succeed you get back a number:
$numberAsString -as [int]
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
note this (powershell coercing feature)
$a = "10"
$a + 1 #second value is evaluated as [string]
101
11 + $a # second value is evaluated as [int]
21
A quick true/false test of whether it will cast to [int]
[bool]($var -as [int] -is [int])