$DriveLetters=Get-Volume ; If (($DriveLetters -contains "D") Fails!!

Hi Guys,
I write a fair amount of PS but this has got me. I bet I’m missing something very basic.

$DriveLetters=Get-Volume |
Where-Object {($.DriveLetter -ne $null) -and ($.DriveType -eq “Fixed”)} |
Select-Object DriveLetter
If (($DriveLetters -contains “D”) -or ($DriveLetters -contains “E”) -or ($DriveLetters -contains “F”)) {

The IF fails! Always false that is. If I add -ExpandProperty to the Select-Object statement it works fine.

Without -ExpandProperty
$DriveLetters
DriveLetter

C

With -ExpandProperty - it a simple array and the IF statement works fine.
$DriveLetters
C

 

Why?? What am I missing here? I’m sure I have missed something very basic while reading Don’s Month of Lunches book.

DriveLetter is a property of each object inside your $DriveLetters array. $DriveLetters is NOT an array of strings. If you pipe $DriveLetters to Get-Member, you’ll see it. Change your if statement to reference that property of the object using the dot operator or use the -ExpandProperty to return the <string> value of that property (then $DriveLetters will be an array of string objects). Here’s a simple illustration to show the problem.

$myobject = [pscustomobject]@{name="Hello"}
$myobject -eq "Hello" #This returns false
$myobject.name -eq "Hello" #this returns true
($myobject | Select-Object name) -eq "Hello" #this returns false
($myobject | Select-Object -ExpandProperty name) -eq "Hello" #this returns true