PowerShell Testing Types and Null
Testing a type is a way to ask what kind of value a variable holds. You also test for null, a special value that means no value has been stored yet.
Ask a value for its type with -is
Write the type in square brackets after -is. A whole number is an [int] and text is a [string].
$age = 31
$age -is [int]
$age -is [string]
$name = "Ana"
$name -is [string]Rule a type out with -isnot
-isnot is the opposite of -is. A decimal number is not a whole number, so it passes an -isnot [int] test.
$price = 9.99
$price -isnot [int]
$price -is [double]
$count = 5
$count -isnot [string]Test for null
$null means no value is stored. Compare with $null on the left, and remember that empty text is different from null.
$nickname = $null
$null -eq $nickname
$null -ne $nickname
$empty = ""
$null -eq $emptyExample
$title = "Ana"
$age = 31
$nickname = $null
"Title is text:"
$title -is [string]
"Age is a whole number:"
$age -is [int]
"Nickname is empty:"
$null -eq $nickname
"Title is empty:"
$null -eq $titleKey points
- Type: the kind of a value, such as a whole number, text, or a decimal number.
- -is tests whether a value is of a given type, such as [int] for a whole number.
- -isnot tests whether a value is not of a given type.
- Null: a special value that means empty, with no value stored at all.
- Put $null on the left side of the comparison, as in $null -eq $name, so the test reads clearly.
In this example, a name, an age, and a nickname are stored, and the nickname holds $null. The type tests confirm the name is text and the age is a whole number. The null tests confirm the nickname is empty and the name is not.
Note
an empty string is not null. Empty text is a value, while null means no value at all.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
If $x = $null, which of these tests returns True?