Search code examples
powershelldirectoryfile-extensionget-childitem

powershell GCI recursively skipping folders and certain file types


Currently I am using this line to collect all files in a certain path (and beyond)

$files = Get-ChildItem -Path $loc -Recurse | ? { !$_.PSIsContainer }

however now ive been asking to generate this list while exclude (for example) all "docx" and "xlsx" files... and folders named "scripts" and their content

I want to read in these file extensions and directory names from a txt file into an array and simply use that array.

Also would speed is important as the functions I will be performing on these files take long enough, I dont need this process slowing down my script 10 full (a bit is okay)

Thanks so much for any inputs

FAILED ATTEMPT:

gi -path H:\* -exclude $xfolders | gci -recurse -exclude $xfiles | where-object { -not $_.PSIsContainer }

I think this works but only does the folder exclusion at the root of the H:\ drive


Solution

  • Something like this? I'm comparing the realative path only(path from $loc) in case $loc includes one of the foldernames to ignore.

    $loc = "C:\tools\scripts\myscripts\"
    $files = Get-ChildItem -Path $loc -Recurse -Exclude *.docx, *.xlsx | ? { !$_.PSIsContainer -and !($_.FullName.Replace($loc,"") -like "*scripts\*") }
    

    Multiple folders(this got ugly):

    #Don't include "\" at the end of $loc - it will stop the script from matching first-level subfolders
    $loc = "C:\tools\scripts\myscripts"
    $ignore = @("testfolder1","testfolder2");
    
    $files = Get-ChildItem -Path $loc -Recurse -Exclude *.docx, *.xlsx | ? { !$_.PSIsContainer } | % { $relative = $_.FullName.Replace($loc,""); $nomatch = $true; foreach ($folder in $ignore) { if($relative -like "*\$folder\*") { $nomatch = $false } }; if ($nomatch) { $_ } }