0 is not [int] in PowerShell?

I understand that (mathematically) 0 is Int. But still

if (0 -as [int]){"Int"}else{"Not"}

      

returns Not

at least for me in PS 2.0.

Is this a bug in v2, or am I not understanding things? I've been working on the problem by testing -as [int] -and -ne 0

, but it's a pretty frustrating feeling, so I hope I'm missing something and have a better answer.

FYI, I'm specifically dealing with the seed computer name that needs the original index or the last computer name that needs indexing. The seed looks like Lab 1 - and the start index can be 0 or can be 1 depending on the situation. I just tested so that the last character was [int]

, knowing that - there would be no int. But when the first computer was Lab 1-00 , because the starting index was 0, I also get not [int]

, and everything gets ugly, and the next computer is Lab 1-0000 . Again, the extra condition works, just wondering if I'm not wrong in my expectation that 0 is [int]

.

+3


source to share


3 answers


The test IF

is performed by calling any expression aside from the parsers and then evaluating the result as [bool]

.

0 -as [int] 

      

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



From the description of the problem, it sounds like you can actually test a string instead of [int].

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

      

Perform this test without throwing an exception.

+3


source


Yes, it 0

has a type [int]

. You can see this for yourself using the method GetType

:

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


PS > 

      



The problem is you are using the wrong operator. You are using -is

for type testing, not -as

:

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

      

+8


source


0 -as [int]

just means 0 is an int. The result of the expression is still 0

, which is implicitly converted to false

.

Instead, you want to use 0 -is [int]

which means is 0 an int

and will evaluate to true

.

Additional literature: get-help about_Type_Operators

EDIT:

The comments below provide an example of how you can evaluate if the last character can be converted to int without throwing an exception:

function CheckLastChar($string){
    $var = 0
    $string -match ".$" | Out-Null

    if ([System.Int32]::TryParse($matches[0], [ref]$var)) {
        "It an int!"
    }
    else {
        "It NOT an int!"
    }
}

      

PS C:\> CheckLastChar("Lab 1-")
It NOT an int!

PS C:\> CheckLastChar("Lab 1-000")
It an int!

      

Although, I must say, mjolinor -as [int] -is [int]

solution is
much nicer.

+5


source







All Articles