Home > database >  Using get-childitem -Exclude to avoid recycle bin, windows, program files
Using get-childitem -Exclude to avoid recycle bin, windows, program files

Time:06-24

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

CodePudding user response:

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}

CodePudding user response:

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?

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

  • Related