Powershell: Why is the Toint32() Method of a String Object always fails? RRS feed

  • Question

  • Hey,

    I have a String object in Powershell, and I want to convert this into a integer. I could see that Object in String class do have Toint32() method provided, and I suppose I should call this one to convert this into a integer, but I always fails. 

    PS C:\windows\system32> $number="12345"
    PS C:\windows\system32> $number.gettype().fullname

    PS C:\windows\system32> $number.Toint32()
    Cannot find an overload for "Toint32" and the argument count: "0".
    At line:1 char:1
    + $number.Toint32()
    + ~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodException
        + FullyQualifiedErrorId : MethodCountCouldNotFindBest

    What is the right way to call this method? 



    Thursday, June 25, 2015 7:29 AM

All replies

  • Jesse,

    This one isn't very intuitive.  .ToInt32() is looking for information on how you format your numbers--where you put your commas, etc.  If you don't give it a format definition, it will use the default definition on your computer.  But the trick is to know how to not give it a definition in such a way that it understands that you aren't giving it one.

    Try this:

    $Number = "12345"

    $Number.ToInt32( $Null )

    Tim Curwick

    Thursday, June 25, 2015 7:42 PM
  • Hello, 

    Alternatively, you can cast your variable to a int this way :

    [int]number = $number

    Thursday, July 18, 2019 11:53 AM