Search code examples
powershellpowershell-2.0subdirectoryget-childitemglob

Filtering child folders with Get-ChildItem -Exclude using a dynamically constructed array of exclusion patterns


I have following folders inside the "clients" directory

Arizona
California
Connecticut
Default
Delaware
Florida
Hawaii
Idaho
Iowa
Maine

I have an array and it has following items:

Write-Host "Printing the array " 
$ExcludeArray

Output----
"Arizona",
"California"  

I'm trying to list the folders inside C:\Users\santhu\Desktop\Clients and exclude the folders in my $ExcludeArray array using following command.

Get-Childitem C:\Users\santhu\Desktop\Clients -Force -Exclude $ExcludeArray

It seems the exclude is not working as expected. I believe the reason could be the items in $ExcludeArray are not in same line. Can someone please suggest me if there is any way to convert them to same line and filter the folders? FYI: the $ExcludeArray items are not static. I cannot write something like $ExcludeArray = "Arizona","California". I'm expecting following output.

Mode                LastWriteTime     Length Name                                                                       
----                -------------     ------ ----                                                                                                                                                                                                       
d----         3/20/2017  12:15 PM            Connecticut                                                                
d----         3/20/2017  12:15 PM            Default                                                                    
d----         3/20/2017  12:15 PM            Delaware                                                                   
d----         3/20/2017  12:15 PM            Florida                                                                    
d----         3/20/2017  12:15 PM            Hawaii                                                                     
d----         3/20/2017  12:15 PM            Idaho                                                                      
d----         3/20/2017  12:15 PM            Iowa                                                                       
d----         3/20/2017  12:15 PM            Maine                                                                      
d----         3/20/2017  12:15 PM            Minnesota 

Solution

  • Try this:

    Get-Childitem C:\Users\santhu\Desktop\Clients\* -Force -Exclude $ExcludeArray
    

    The exclude and include switch is a bit tricky here. It works on the last mentioned path. So wildcard should do your work. Make sure you are not having any double quotes inside the array.