PowerShell: When does zero equal one? (Length property of a Directory)

You learn the most interesting things when teaching a class, especially when an off the cuff demo goes wrong.

During a simple demo of a calculated or derived column I did this:

For files, the output was as expected:

But for directories it returned this:

While the FileInfo object does have a Length property, the DirectoryInfo object does not. So what should we expect when both files and directories are in the same pipeline? Directories usually display a blank column for Length. Is this a Null? Is this an empty or one space string? Or is it just skipped because DirectoryInfo objects don't have a Length property?

Noting that 9.53674E-07 is 1 / 1MB, PowerShell is returning a 1 for the missing Length property, and not a zero or null as I was expecting.

Turns out that Length is both a property of FileInfo objects, and also a property of all PowerShell objects. In my example, DirectoryInfo objects did not have a Length property so $_.Length returns the underlying object's Length property.

Here's an example of a new "Object". Note that PowerShell thinks it has a length of 1 even though Length is not one of its properties. If it's not a defined property, where does it come from? PowerShell seems to treat all objects as collections, even if it is a single item. Collections have both a Count and a Length property. So, $x has a Length (and a Count) of 1.

There's a hint in the PowerShell help files about this. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_properties?view=powershell-7  (or in PowerShell help about_Properties)

And, as the Help file says, it was different in PowerShell 2.0. If I launch PowerShell with the -Version 2.0 option, I actually get the result I expected in the original demo!


No comments:

Note to spammers!

Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.