locked
Get-ChildItem exclude folders PowerShell 2.0 RRS feed

  • Question

  • Guys, I'm trying to run the following code to get the folder names inside the source, but I need to exclude a few folders.  This is being done in PowerShell 2.0, I have no other choice.

    The thing is, that if I exclude only one folder, it works, but when I have to do more than 1, it doesn't exclude them.

    $SourceRoot = "C:\Source"
    #This array set will be used to exclude folders I don't want to bring over.
    
    $Exclude = "Folder1", "Folder2"
    
    #This gets me the folder names only
    $Folders = gci -Path $SourceRoot  | Where {($_.PSIsContainer) -and ($_.Name -notlike $Exclude)}

      
    Monday, August 10, 2015 5:16 PM

Answers

  • I followed your same logic, and this is what worked!


    $Exclude = @("Folder1","Folder2") 
    
    $Folders = gci -Path $SourceRoot  | Where {($_.PSIsContainer) -and ($Exclude -notcontains $_.Name)}


    • Marked as answer by Diango Monday, August 10, 2015 8:04 PM
    Monday, August 10, 2015 5:53 PM

All replies

  • reverse the comparison to avoid issues comparing a single object to an array.  This way it looks at each item in the array to make sure it doesn't match name.

    $Exclude = @("Folder1", "Folder2")
    
    $Folders = gci -Path $SourceRoot  | Where {($_.PSIsContainer) -and (!$Exclude.Contains($_.Name))}
    

    Monday, August 10, 2015 5:23 PM
  • This works for 3.0 and up, but I need it to work for 2.0.  It's a tough requirement :(
    Monday, August 10, 2015 5:45 PM
  • gci -Path $SourceRoot   | Where {$_.PSIsContainer -and $_.Name -notmatch 'folder|folder2'}


    \_(ツ)_/

    Monday, August 10, 2015 5:51 PM
  • I followed your same logic, and this is what worked!


    $Exclude = @("Folder1","Folder2") 
    
    $Folders = gci -Path $SourceRoot  | Where {($_.PSIsContainer) -and ($Exclude -notcontains $_.Name)}


    • Marked as answer by Diango Monday, August 10, 2015 8:04 PM
    Monday, August 10, 2015 5:53 PM