Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Powershell what is the idiomatic way of converting a string to an int?

Tags:

powershell

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?

like image 554
John Kane Avatar asked Mar 14 '12 11:03

John Kane


People also ask

How do I convert a string to an int in PowerShell?

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.

Which method converts a string into an int?

ToInt32(String) method to convert an input string to an int.


2 Answers

You can use the -as operator. If casting succeed you get back a number:

$numberAsString -as [int] 
like image 120
Shay Levy Avatar answered Sep 17 '22 14:09

Shay Levy


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 
like image 29
CB. Avatar answered Sep 19 '22 14:09

CB.