PowerShell Compare-Object doesn’t handle null values

I thought I'd run into a bug with the Compare-Object cmdlet in PowerShell version 5.1 earlier today.

1$DriveLetters = (Get-Volume).DriveLetter
2$DriveLetters
3Compare-Object -ReferenceObject $DriveLetters -DifferenceObject $DriveLetters

diff-null1a.jpg

1Compare-Object : Cannot bind argument to parameter ‘ReferenceObject’ because it is null.
2At line:1 char:33
3+ Compare-Object -ReferenceObject $DriveLetters -DifferenceObject $Driv …
4+ ~~~~~~~~~~~~~
5+ CategoryInfo : InvalidData: (:) [Compare-Object], ParameterBindingValidationException
6+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.CompareObjectCommand

Running the same commands on a VM with PowerShell version 5.0 completed without issue so it initially appeared to be a problem with the Compare-Object cmdlet in PowerShell version 5.1.

The error was actually due to Get-Volume returning several results that didn't have a drive letter on the system running PowerShell version 5.1.

1Get-Volume

diff-null2a.jpg

There just happened to be no drives without letters on the VM that the results were being compared to. In other words, all drives had drive letters on the comparison VM. This explains why it succeeded without error on that particular system.

Once the entries without drive letters were filtered out on the system running PowerShell version 5.1, the command completed successfully.

1$DriveLetters = (Get-Volume).Where({$_.DriveLetter}).DriveLetter
2$DriveLetters
3Compare-Object -ReferenceObject $DriveLetters -DifferenceObject $DriveLetters

diff-null3a.jpg

I would like to thank both Jeff Hicks and Aleksandar Nikolic for their assistance in helping determine the source of the problem. I thought I'd share this problem because I'm sure it's something that others will run into.

µ