Determining when an object or custom object is empty

You want to determine whether a custom object is more than the empty shell of an object.

When you need this:
  1. You are using a function that returns a custom object. 
  2. You do not control what is returned.  
  3. If the function returns no values, you receive a custom object shell.  The object shell would be equivalent to using the command:  $SampleObject = @{}

The key here is that you cannot control alter the function that returns the object. The called function does not structure an object unless it contains values.  When the minimal object is returned, it an object with only methods and, perhaps, properties.  What it lacks are the Note Properties associated with the object having values.  The object created from the returned function value is checked for Note Properties.  Here is an example:

# You are creating an object called $SourceDateTimeProperties.
# The base data set is $SourceProperties. For this example, the $SourceProperties does not contain any objects of the type 'DateTime'
# You are filtering on a type of 'DateTime' using a function called 'Select-KCTNSPCustomListPropertiesByType.
$SourceDateTimeProperties = $SourceProperties |
.\Select-KCTNSPCustomListPropertiesByType -ByType "DateTime"
# SourceDateTimeProperties is a shell
# The following test checks whether $SourceDateTimeProperties has any Note Properties. if it does, then the test results in a $True.
(($SourceDateTimeProperties.psobject.Properties.MemberType) -contains "NoteProperty")

Alternative:  If Can Alter the Returned Function

If you control the called function, you could:

  1. You could populate the an empty object with the properties that the object should return.  You could then count the occurrence of values in the property.  if the count is zero, the object is empty.
  2. return an error code which you check in the calling script or function.

Links

An excellent summary of alternatives when faced with an empty object structure:  What operator should be used to detect an empty psobject?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>