The only method I have found is a direct cast:
> $numberAsString = "10" > [int]$numberAsString 10
Is this the standard approach in Powershell? Is it expected that a test will be done before to ensure that the conversion will succeed and if so how?
Use [int] to Convert String to Integer in PowerShell The data type of $a is an integer . But when you enclose the value with " " , the data type will become string . To convert such string data type to integer, you can use [int] as shown below.
ToInt32(String) method to convert an input 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With