Powershell extension method

We are testing our Powershell Module with Pester. Since the data is some sort of graph we need to work with indexers / lists all the time. After a small brainstorm session we decided on an Extension Method approach.

Reading the post Extension Methods in Windows PowerShell from Bart de Smet we started to develop. After some attempts we ended up with an XML containing the scriptmethod we needed. Important tip is to handle the $args in a special way: assign to local variable to prevent getting lost …

<?xml version="1.0" encoding="utf-16"?>
<Types>
 <Type>
  <Name>Company.RootNode</Name>
   <Members>
    <ScriptMethod>
     <Name>GetById</Name>
     <Script>
      switch ($args.Count) {
       1 { $req = $args[0];[System.Linq.Enumerable]::First($this.Children, [System.Func[Company.Node,System.Boolean]]{ param($x) $x.Id -eq $req })}
 default { throw "No overload for Uses takes the specified number of parameters." }
      }
    </Script>
   </ScriptMethod>
  </Members>
 </Type>
</Types>

You can load the extension method into powershell with the following command, where RootNodeExtensions.ps1xml is the name of the file containing the xml

Update-TypeData -prependPath RootNodeExtensions.ps1xml

Now the RootNode has the extension method GetById, so we can use $root.GetById(“12345″) that returns the first node in the Children property that has the Id==”12345” or throws an exception. Sounds like testing 😉

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , , . Bookmark the permalink.

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.