I've stumbled across an odd situation in PowerShell 5.1 (Windows 10) where ConvertTo-Json
produces {}
instead of null
for an apparently null valued object:
[CmdletBinding()]
param()
function main() {
$foo1 = $null
Write-Verbose ("foo1 null? " + ($null -eq $foo1))
$foo2 = try{1/0}catch{}
Write-Verbose ("foo2 null? " + ($null -eq $foo2))
$foo3 = try{1/0}catch{$null}
return [PSCustomObject]@{"foo1"=$foo1; "foo2" = $foo2; "foo3" = $foo3} | ConvertTo-Json
}
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
main
Running this cmdlet -verbose
shows two apparently $null
variables which are serialized differently by ConvertTo-Json
:
VERBOSE: foo1 null? True
VERBOSE: foo2 null? True
{
"foo1": null,
"foo2": {}
"foo3": null
}
What is going on here - are there different kinds of $null
?
I can't to $foo2 | gm
or $foo2.GetType()
because $foo2
is null.