Hi folks
Recently I discovered some WTF which I would like to discuss.
$p = New-Object -TypeName System.Diagnostics.Process
then check
$p.ExitCode
returns nothing
$p.ExitCode -eq $null
returns True
Let’s check the type of ExitCode property
$p | Get-Member -Name ExitCode
returns
TypeName: System.Diagnostics.Process
Name MemberType Definition
---- ---------- ----------
ExitCode Property System.Int32 ExitCode {get;}
So we see a return type is System.Int32 which is not nullable. So ExitCode property cannot return null.
Hmm… How is that possible?
Let’s try another way
$p.get_ExitCode()
it returns
Exception calling "get_ExitCode" with "0" argument(s): "No process is associated with this object." At line:1 char:16 + $p.get_ExitCode <<<< () + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException
So clearly when you get a property which throws an exception you swallows the exception and returns $null
I did not find any PowerShell documentations that states such behavior.
The only thing I found is a similar StackOverflow question about calculated properties.
So in cases if you need to get a property and you don’t want to swallow exceptions you have to use get_Property() approach