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

Welcome Forums General PowerShell Q&A $DriveLetters=Get-Volume ; If (($DriveLetters -contains “D”) Fails!!

Viewing 1 reply thread
  • Author
    • #214713
      Topics: 1
      Replies: 2
      Points: 3
      Rank: Member

      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

      With -ExpandProperty – it a simple array and the IF statement works fine.


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

    • #214737
      Topics: 4
      Replies: 82
      Points: 251
      Helping Hand
      Rank: Contributor

      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


      • This reply was modified 1 month, 3 weeks ago by Mike R..
Viewing 1 reply thread
  • You must be logged in to reply to this topic.