Type operators can be used to validate types for .NET objects. It is important that you understand that objects of different types can behave differently. You will need to know how to identify and validate the types, especially in large and complex scripts:
Operator
|
Meaning
|
Description
|
-is
|
Compare types
|
Validates if the type of the object on the left is the same as the one on the right. |
-isNot
|
Compare types (inverted)
|
Validates if the type of the object on the left is not the same as the one on the right. |
-as
|
Cast
|
Converts the object on the left to the specified type. |
.getType()
|
Show type
|
Shows the .NET Function for every object. Retrieves the type of the object. |
Some examples are as follows:
# Validate numeric values
64 -is [int] # true
64 -is [float] # false
64 -is [decimal] # false
(99999999999).GetType() #Int64
99999999999 -is [Int64] #true
99999999999 -isNot [Int] #true
9999999999999999999999999 -is [decimal] #true
# Validate array
(Get-Process) -is [Array]
("b","c") -is [Array]
@(1,2,"d") -is [Array]
# Validate other .NET objects
(Get-Date) -is [DateTime] #True
((Get-Date).ToString()) -is [DateTime] #false
(Get-Process PowerShell)[0] -is [System.Diagnostics.Process]
# Casting
(1000 -as [DateTime]) -is [DateTime] #true
([int]"676").GetType() #Int32
[int]"676f" #Error
[int]"676.765468" # 677 - automatic rounding to the specified type
As you can see, there are different ways to validate types. The numeric values will automatically modify types, depending on initial length; with casting, you can easily convert between types. It is probably not the preferred way to accomplish this, because you could easily run into errors, as demonstrated in the preceding example. We will take a dedicated look at other converting techniques later on.