I've started using PowerShell to get some things done and played with the variable $null
in PowerShell.
I've encountered the problem that when I assign the variable $null
to a variable defined in a class, the test returns false
not true
.
Example Code:
class test {
[string]$test1
}
$test = [test]::new()
$test.test1 = $null
$null -eq $test2 # tests true
$null -eq $test.test1 # tests false
Now the test of the undefinded variable $test2
returns true
as every undefined variable in PowerShell is assigned $null
.
But if I test the property test1
of the object test
which I assigned $null
tests false
for $null
Is it because in PowerShell $null
is an object with the value $null
and now the property of the object is not $null
as it has the object $null
assigned to it with an empty value?
I've read into the docs of Microsoft "Everything you wanted to know about $null", but it does not enlighten me.
If I do not initialize the variable, then it will test true
for $null
.
$test.test1
is not $null
, it's empty string (because you explicitely defined it's value to be [string]
):
C:\> $test.test1.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
Proof:
C:\> $test.test1 -eq ""
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With