Search code examples
powershellget-childitem

PowerShell GetChildItem exclude file type in base folder but include same file type from sub folder


I'm trying to find a method of getting GetChildItem to include all .xml files found in subfolders, but exclude the .xml files found in the base folder.

My folder structure looks like this:

MySubFolder\IncludeThis.xml
MySubFolder\AlsoIncludeThis.xml
AnotherSubFolder\IncludeThis.xml
AnotherSubFolder\AlsoIncludeThis.xml
ExcludeThis.xml
AlsoExcludeThis.xml

I've tried using -Include and -Exclude arguments, without any luck, as these arguments seem to only work on file types and cannot be set to work only on certain folders.

Anyone know how to get GetChildItem to filter out the .xml files from the base folder only?

PS) I won't know the names of the sub folders that exist, when using the command.


Solution

  • You need to get the subfolders in a first step and search them for xml Files, e.g.:

    #Get list of subfolders
    $folders = get-childitem -Path [path] -Directory
    
    #Get xml files in subdirectories
    $xmlFiles = get-childitem -Path $folders.fullname -Filter '*.xml' -File -recurse