Skip to main content

Filter an Object to Help Send Data to a Cmdlet via the Pipeline.

I took a question posted on this blog about a unique Exchange issue that an administrator was having.  They needed to take a CSV file containing names and pipe it to cmdlets for Exchange Server to take actions on.  The problem is that one of the parameters of a cmdlet would not accept the input. 

The code below is designed to take any object and get a list of its properties.  (In the Exchange Administrators case, the object was created using the Import-CSV cmdlet.) This cmdlet also took a look at the cmdlet that you intend to pipe the final data to.  It will extract the parameters of this cmdlet.  It then compares the each property of the object with the parameters of the cmdlet.  If there is a match, the property will be passed to the pipeline.  If not, it will be dropped. 

In the help file, two examples are given.  One that has a cmdlet in which all parameters accept values via the pipeline and one that does not.  To read more about passing parameters that do not accept input via the pipeline, read here.

And now for the good stuff:

 

Function Merge-ParameterData

{

[cmdletbinding(HelpUri="http://get-help-jason-yoder.blogspot.com/2013/03/merge-parameterdata.html")]

Param(

    [Parameter(Mandatory=$True,

               ValueFromPipeline=$True,

               Position=0)]

               $Data,

    [Parameter(Mandatory=$True,

               ValueFromPipeline=$False,

               Position=1)]

               $Cmdlet          

)

    Begin

    {

        Write-Verbose "==== Cmdlet: Merge-ParameterData ===="

       

        Function Get-ParameterList

        {

            [cmdletBinding()]

            Param ($Cmdlet)

                Write-Verbose "== Function: Get-ParameterList =========================="

                Write-Verbose "Parameter - `$Cmdlet: $Cmdlet"

                $List = (get-help $Cmdlet -parameter * |

                    Select-Object -Property Name |

                    ForEach -Process {$_.name})

 

                Write-Verbose "Sending $($List.count) Items to the pipeline."

                Write-Output $List

                Write-Verbose "__ End Function: Get-ParameterList ____________________"

            <#

            .SYNOPSIS

            Extracts cmdlet parameters

 

            .DESCRIPTION

            Extracts the parameters from a supplied cmdelt and sends then as a collection

            into the PowerShell Pipeline.

 

            .PARAMETER Cmdlet

            The name of the cmdlet whose parameters you want to extract.

 

            .EXAMPLE

            Get-ParameterList Set-MailContact

 

            Sends a collection of strings containing the names of all of the parameters

            avaliabe to the cmdlet Set-MailContact.

            #>

        } # End: Function - Get-ParameterList =========================================

   

   

        Function Merge-Objects

        {

        [cmdletbinding()]

        Param ($ParamList,$Data)

            Write-Verbose "== Function: Merge-Objects =="

           

            # Create a new object to hold the data.

            $OutputObj = New-Object -TypeName PSObject

           

            # Cycle through the data to find properties that

            # match.  If matching properties are found, add them to the

            # $OutputObject.

           

            ForEach ($Item in $ParamList)

            {

               If ($Data.($Item) -ne $Null)

               {

                $OutputObj | Add-Member -MemberType NoteProperty `

                    -Name $Item -Value $Data.($Item)

               }

            }

       

            Write-Output $OutputObj

        } # End: Function - Merge-Objects =========================================

   

    } # End: Begin Block ----------------------------------------------------------

   

   

    Process{

        Write-Verbose "Process Block Started"

        Write-Verbose "Getting list of parameters from $($Cmdlet)"   

       

        # Get a list of parameters from the supplied cmdlet.

        $ParamList = Get-ParameterList -Cmdlet $Cmdlet

 

        # Write the object to the pipeline.

        Write-Output (Merge-Objects -ParamList $ParamList -Data $Data)

 

    } # End: Process Block ----------------------

   

   

    End

    {

        Write-Verbose "-------------------------------------------------------"

        Write-Verbose "-- Cmdlet: Merge-ParameterData Completed             --"

        Write-Verbose "-- Copyright 2013 MCTExpert, Inc.                    --"

        Write-Verbose "-- All Rights Reserved                               --"

        Write-Verbose "-------------------------------------------------------"              

    }

 

<#

.SYNOPSIS

Compares the properties of an object with the parameters of a cmdlet.

 

.DESCRIPTION

Takes an object and examines the properties of the object and the parameters

of a cmdlet.  It then produces an object in the pipeline of any properties

from the object that match a parameter of the cmdlet.  Any properties from the

object that do not have a matching parameter in the cmdlet will be dropped.

 

===============================================================================

== Cmdlet: Merge-ParamarterData                                              ==

== Version 1.0                                                               ==

==---------------------------------------------------------------------------==

== Author: Jason A. Yoder                                                    ==

== Company: MCTExpert, Inc.                                                  ==

== Blog: MCTExpert.Blogspot.com                                              ==

== Twitter: @JasonYoder_MCT                                                  ==

==---------------------------------------------------------------------------==

== License Information:                                                      ==

== Copyright 2013 - MCTExpert, Inc.                                          ==

== This code is licensed for personal use only.  This code may not be        ==

== re published or distributed in whole or in part without the express       ==

== written consent of MCTExpert, Inc.  All rights reserved.                  ==

==---------------------------------------------------------------------------==

== Disclaimer: The user takes full responsibility for the execution of any   ==

== PowerShell code.  This code is provided without warranty or support.      ==

== As with all PowerShell code, review it and test it in a test environment  ==

== prior to using it in a production environment.  The user takes complete   ==

== responsibility for the results of executing this code.                    ==

===============================================================================

 

.PARAMETER Data

The object that you want to example to send to the cmdlet.

 

.PARAMETER Cmdlet

The cmdlet that you want to send the object to.

 

.EXAMPLE

IMPORT-CSV "C:\Process.csv" |

Merge-ParameterData -Cmdlet Get-Process|

Get-Process

 

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName                                                                                      

-------  ------    -----      ----- -----   ------     -- -----------                                                                                      

    398      30    10664      11580   156    44.98   3472 ANT Agent                                                                                        

     76      18     6560       7052    84     0.64   7024 calc                                                                                             

   1157      70    64452      94348   399    27.28   7504 explorer

 

Takes a CSV file and compares the property names of the imported objects

to the parameter list of Get-Process.  It them pipes the results to

Get-Process.

 

.EXAMPLE

Import-Csv C:\PS\Contacts.csv | Mearger-ParameterData -Cmdlet New-MailContact |

ForEach -Process {New-MailContact -Name $_.Name -DisplayName $_.DisplayName `

 -ExternalEmailAddress $_.ExternalEmailAddress}

 

Creates mail contacts from a CSV file. The New-MailContact cmdlet

does not accept input from the pipeline on the Name or the ExternalEmailAddress

Parameters.  This example shows you how to get around this issue.

 

#>

} # End: Cmdlet: Merge-ParameterData

 

 

 

Comments

Popular posts from this blog

Adding a Comment to a GPO with PowerShell

As I'm writing this article, I'm also writing a customization for a PowerShell course I'm teaching next week in Phoenix.  This customization deals with Group Policy and PowerShell.  For those of you who attend my classes may already know this, but I sit their and try to ask the questions to myself that others may ask as I present the material.  I finished up my customization a few hours ago and then I realized that I did not add in how to put a comment on a GPO.  This is a feature that many Group Policy Administrators may not be aware of. This past summer I attended a presentation at TechEd on Group Policy.  One organization in the crowd had over 5,000 Group Policies.  In an environment like that, the comment section can be priceless.  I always like to write in the comment section why I created the policy so I know its purpose next week after I've completed 50 other tasks and can't remember what I did 5 minutes ago. In the Group Policy module for PowerShell V3, th

Return duplicate values from a collection with PowerShell

If you have a collection of objects and you want to remove any duplicate items, it is fairly simple. # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   # Remove the duplicate values. $Set1 | Select-Object -Unique 1 2 3 4 5 6 7 What if you want only the duplicate values and nothing else? # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   #Create a second collection with duplicate values removed. $Set2 = $Set1 | Select-Object -Unique   # Return only the duplicate values. ( Compare-Object -ReferenceObject $Set2 -DifferenceObject $Set1 ) . InputObject | Select-Object – Unique 1 2 This works with objects as well as numbers.  The first command creates a collection with 2 duplicates of both 1 and 2.   The second command creates another collection with the duplicates filtered out.  The Compare-Object cmdlet will first find items that are diffe

How to list all the AD LDS instances on a server

AD LDS allows you to provide directory services to applications that are free of the confines of Active Directory.  To list all the AD LDS instances on a server, follow this procedure: Log into the server in question Open a command prompt. Type dsdbutil and press Enter Type List Instances and press Enter . You will receive a list of the instance name, both the LDAP and SSL port numbers, the location of the database, and its status.