Home > Back-end >  PowerShell GetChildItem exclude file type in base folder but include same file type from sub folder
PowerShell GetChildItem exclude file type in base folder but include same file type from sub folder

Time:10-25

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.

CodePudding user response:

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

CodePudding user response:

While searching the the answer to this question, I came up with a method of achieving what I needed, by combining results from multiple calls to Get-ChildItem:

#Find the list of all files and folders, including files in sub folders, from a directory:
$All = Get-ChildItem -Recurse

#Find a list of items to exclude from the first list:
$Exclude = Get-ChildItem *.xml

#Remove excluded items from the list of all items:
$Result = $All | Where-Object {$Exclude.FullName -NotContains $_.FullName}

#These terms can be combined into a single difficult-to-read statement:
Get-ChildItem -Recurse | Where-Object {(Get-ChildItem *.xml).FullName -NotContains $_.FullName}
  • Related