PowerShell .NET property access swallows exceptions

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

Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged , . Bookmark the permalink.

One Response to PowerShell .NET property access swallows exceptions

  1. Pingback: Powershell Start-Process WTF | mnaoumov.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s