I’ve been fighting a problem today whereby the PowerShell Where-Object commandlet was returning results of varying object types from the same XML document. Specifically, when trying to check for the numbers of adds/deletes/updates from a CSExport xml file, where I had isolated the deltas to the following:
$deltas = $csdata.SelectNodes("//cs-objects/cs-object[@object-type='$addObjectClass']/pending-import/delta")
If I then used the Where-Object construct as follows:
$deletes = $deltas | Where-Object {$_."operation" -eq "delete"}
… I would either get an object back of type System.Xml.XmlLinkedNode or System.Xml.XmlNodeSet. Because I simply wanted to access the Count method of the XmlNodeSet, this was failing (returning nothing) when the result was of type System.Xml.XmlLinkedNode. In looking at the available methods of my $deltas System.Xml.XmlNodeSet variable I noticed the Where method … another piece of pure gold! The syntax is slightly different if I use this:
$deletes = $deltas.Where({$_."operation" -eq "delete"})
… BUT, the result is always System.Object[].
This means that regardless of what XML I am confronted with, the most reliable means of counting the number of changes is to use the “Where” method of the System.Xml.XmlNodeSet class.
One step closer to a reliable means of consistently counting Pending Import and Pending Export changes from either my CSExport or Run Profile audit drop (xml) files :).
Hi Bob,
Many PowerShell commands and .NET methods may return one or many objects, which can cause challenges when you want to get the count of objects returned. When you want to get a count, regardless of whether you are returned no items, one item, or many items from a command, wrap the command in array enclosures. Using your example above, that would look like this:
$deletes = @($deltas | Where-Object {$_.”operation” -eq “delete”})
When you do that you are guaranteed to get an array, and you can reference the Count property to see how many items you have.
Hope this helps!
Kirk out.