PowerShell: Function to see if a Set of Properties Are on a Custom Object

I’ve been using scripts that pass loads of custom objects back and forth as function parameters.  In some cases these objects are built dynamically so they could have different properties on them.

It’s useful then to check if a particular set of parameters are on an object.

Hence;  this function!  (After the line!)

Full function is below with some words after 🙂

<# .SYNOPSIS This takes a passed object and compares its properties against a list of names. It returns true if all the properties are present on the object. .DESCRIPTION This takes a passed object and compares its properties against a list of names. It returns true if all the properties are present on the object. .PARAMETER $PassedObject The object to check the properties on. .PARAMETER $ParameterNames An array of property names to check for. If all are present $True is returned. #> 
function Get-AllParametersArePresentOnObject
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$True)]
        [PSObject]$PassedObject,
        [Parameter(Mandatory=$True)]
        [string[]]$ParameterNames
    )
    Write-Log "Started running $($MyInvocation.MyCommand)" -Emphasis
    $ObjectParameterNames=$PassedObject | Get-Member -MemberType All | Select-Object -ExpandProperty Name
    Write-Log "Stopped running $($MyInvocation.MyCommand)" -Emphasis
    Return @(Compare-Object -$ObjectParameterNames $ParameterNames -ExcludeDifferent -IncludeEqual).Count -eq $ParameterNames.Count

}

It’s actually pretty straight-forward.  The function is passed an object and an array of parameter names;  if the parameters are on the object the function returns $True.

First it gets a list of all the parameters on the passed object with;

$ObjectParameterNames=$PassedObject | Get-Member -MemberType All | Select-Object -ExpandProperty Name

This returns an array of parameter names.  It uses -ExpandProperty so that just the names are returned as an array of strings.

Then it compares the passed parameter list with the array it just created;

Return @(Compare-Object -$ObjectParameterNames $ParameterNames -ExcludeDifferent -IncludeEqual).Count -eq $ParameterNames.Count

It uses Compare-Object but we’re only interested in matches between the two lists;  the script uses -ExcludeDifferent and -IncludeEqual.

Finally it compares if the the count of matches is equal to the number of parameters we’re interested in.

 

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