Fetch all the files in a folder but exclude all the files in a sub folder by using powershell

46 Views Asked by At

I have a powershell script to fetch all the files in a folder but exclude all the files in a sub folder. I am using the following script, but not giving the expected results.

Get-ChildItem -Path $srcpath -Force -Exclude "Monthly Reports" -Recurse

Note: Trying to exclude the files in the sub folder "Monthly Reports"

1

There are 1 best solutions below

0
Santiago Squarzon On BEST ANSWER

-Exclude preforms exclusions based on the item's .Name property, and what you need in this case is to exclude them based on their .FullName property, a layer of filtering on that property is required:

Get-ChildItem -Path $srcpath -Force -Recurse |
    Where-Object FullName -NotMatch '[\\/]Monthly Reports[\\/]?'

If you want to exclude all childs of that folder but not the folder itself you can change the pattern to:

Get-ChildItem -Path $srcpath -Force -Recurse |
    Where-Object FullName -NotMatch '[\\/]Monthly Reports[\\/].'