0 not an [int] in PowerShell? 0 not an [int] in PowerShell? powershell powershell

0 not an [int] in PowerShell?


Yes, 0 is of type [int]. You can see this for yourself using the GetType method:

PS > (0).GetType()    IsPublic IsSerial Name                                     BaseType                  -------- -------- ----                                     --------                  True     True     Int32                                    System.ValueType          PS > 

The problem is that you are using the wrong operator. You use -is to test type, not -as:

PS > 0 -is [int]TruePS > if (0 -is [int]) {"Int"} else {"Not"}IntPS > 


0 -as [int] simply means cast 0 as an int. The result of the expression is still 0, which implicitly converts to false.

Instead you want to use 0 -is [int], which means is 0 an int and would evaluate to true.

Further reading: get-help about_Type_Operators

EDIT:

Per your comments below, here is an example of how you might evaluate if the final character can be converted to an int without throwing an exception:

function CheckLastChar($string){    $var = 0    $string -match ".$" | Out-Null    if ([System.Int32]::TryParse($matches[0], [ref]$var)) {        "It's an int!"    }    else {        "It's NOT an int!"    }}
PS C:\> CheckLastChar("Lab 1-")It's NOT an int!PS C:\> CheckLastChar("Lab 1-000")It's an int!

Although, I have to say mjolinor's -as [int] -is [int] solution is much nicer.


The IF test is performed by invoking whatever expression is in side the parens, and then evaluating the result as [bool].

0 -as [int] 

returns 0. When an [int] is evaluated as [bool] (true/false) 0 is $false, so the test always fails.

From the description of the problem, it sounds like you might actually be testing a string instead of an [int].

  if ($var -as [int] -is [int]) {"Int"} else {"Not"}

Should perform that test without throwing an exception.