powershellpowershell-2.0powershell-3.0powershell-4.0

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


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"


Solution

  • -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[\\/].'