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

前端 未结 7 656
栀梦
栀梦 2020-12-05 12:32

The only method I have found is a direct cast:

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

Is this the standard approach in

7条回答
  •  长情又很酷
    2020-12-05 13:18

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

    But, depending on what you need you can just put a string containing a number on the right of an arithmetic operator with a int on the left the result will be an 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 Problem

提交回复
热议问题