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.

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

diff-null1a.jpg

_Compare-Object : Cannot bind argument to parameter ‘ReferenceObject’ because it is null. At line:1 char:33 Compare-Object -ReferenceObject $DriveLetters -DifferenceObject $Driv …

CategoryInfo : InvalidData: (:) [Compare-Object], ParameterBindingValidationException
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.

```powershell
Get-Volume
```

![diff-null2a.jpg](/images/2018/01/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.

```powershell
$DriveLetters = (Get-Volume).Where({$_.DriveLetter}).DriveLetter
$DriveLetters
Compare-Object -ReferenceObject $DriveLetters -DifferenceObject $DriveLetters
```

![diff-null3a.jpg](/images/2018/01/diff-null3a.jpg)

I would like to thank both [Jeff Hicks](https://twitter.com/JeffHicks) and
[Aleksandar Nikolic](https://twitter.com/alexandair) 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.

µ