1

I am trying to exclude the "recycle bin", "Windows", and "Program Files" folders in my recursive call to Get-ChildItem.

I figured it would just be -Exclude '$Recycle.Bin', 'Windows', 'Program Files' or -Exclude 'C:\$Recycle.Bin', 'C:\Windows', 'C:\Program Files', but neither of these give me the wanted result. Any ideas? Thanks

zett42
  • 25,437
  • 3
  • 35
  • 72
mellinka
  • 23
  • 3
  • 1
    Unfortunately `-Exclude` doesn't work recursively. It is just applied to the file/directory name, but child items are still processed. https://stackoverflow.com/search?q=%5Bget-childitem%5D+exclude+recursive – zett42 Jun 23 '22 at 18:44
  • 1
    Does this answer your question? [How to exclude files and folders from Get-ChildItem in PowerShell?](https://stackoverflow.com/questions/61934452/how-to-exclude-files-and-folders-from-get-childitem-in-powershell) – zett42 Jun 23 '22 at 18:45

2 Answers2

2

Exclude does not filter out child objects found within excluded directories when you use the Recurse option. The answer over here contains a good explanation about this:

How to exclude files and folders from Get-ChildItem in PowerShell?

You can accomplish what you want by stringing together multiple calls as the other answer suggested. Here is a sample one-liner PowerShell command that lists all files greater than 1GB in size, excluding the directories you listed:

Get-ChildItem C:\ -Directory | Where-Object Name -NotIn @('Windows','Program Files','$Recycle.Bin') | % { Get-ChildItem -File $_.FullName -Recurse} | Where-Object {($_.Length /1GB) -gt 1} | Sort -Descending -Property Length | Format-Table Length, FullName -AutoSize -Wrap

Here is a breakdown of how this one-liner works:

  1. The first Get-ChildItem returns all Top Level directories under your C:\ drive.
  2. These directories are then piped (|) into the Where-Object cmdlet, where we use the -NotIn parameter to specify an array of directory names to exclude.
  3. This filtered set of Top Level directories is then passed into the ForEach-Object cmdlet denoted here with the % alias.
  4. Each of the directories is then passed in one-by-one into another Get-ChildItem cmdlet which does the recursive search you desire. (Note that I used the -File filter to only return files)

That should cover what you asked for in your original question. The second Where-Object cmdlet filters files over 1GB in size, then those get sorted by file size, and the result is printed out in table format. You probably want to replace these parts with whatever you were trying to do.

If you want to use different types of filters instead of the NotIn filter, take a look at all the other options availabe in the Where-Object doc.

1

You could use this syntax instead to achieve the same effect.

$Directories = Get-ChildItem c:\ -Directory | Where-Object Name -NotIn @('Windows','Program Files','$Recycle.Bin')
$Output = $Directories | % { Get-ChildItem $_.FullName -Recurse}
Fm253
  • 46
  • 5