Wednesday, February 20, 2013

Get-Member on empty collections

PowerShell's pipeline just loves to unravel collections, with the result that sometimes, when you want to do something on the collection itself, you can't. Like with Get-Member:
$blah.Catalogs | Get-Member Get-Member : No object has been specified to the get-member cmdlet.
What happened? Did $object.Catalogs return null, or did it return an empty IEnumerable? This has bitten me a few times, especially when poking around in an API for the first time (ie: at this point I have no idea what 'Catalogs' is, whether it's ICollection or whatever).

The answer, I realize, is to avoid the pipeline:
Get-Member -inputObject:$blah.Catalogs TypeName: BlahNamespace.BlahCollection Name MemberType Definition ---- ---------- ---------- Add Method System.Void Add(Microsoft.SqlServer.Management.IntegrationSer... Clear Method System.Void Clear()
Much better

1 comment:

piers7 said...

Related: in PowerShell 1 and 2 if you send an empty collection / array to the pipeline, you'll get a null passed (once) to the downstream expressions.

In PowerShell v3 this no longer happens, and piping an empty array causes downstream pipelines to see no data instead.

Popular Posts