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 😉