Powershell Skip Folder Using Get-Childitem

Powershell Skip Folder Using Get-Childitem

Part of a PowerShell script I am running, I want it to completely ignore a specific folder or path.

I've tried to use the -notmatch and also -notlike operator. But it seems it will still go through every file in that folder. While it won't process items in that folder, so I get the desired result, there's still hundreds of thousands of files in that folder and can take a long time just to run through the script. I just want it to completely bypass that folder.

Here is the part of the script that I have:

$allfiles = Get-ChildItem -path $BaseDirectory -Force -File -Recurse | ? { $_.FullName -notmatch 'DATA\SHARED\GAMES\STEAM\SteamLibrary' } | select-object Name,FullName,Length

I have also tried:

Where { $_.FullName -notlike '*\DATA\SHARED\GAMES\STEAM\SteamLibrary\*' }

Is there a better way to have it just skip that folder altogether, preferably using the relative path? Or even just folder name SteamLibrary

Thanks!

1 Answer

Get all the directories exceept SteamLibrary & then get the files in each:

$allfiles = Get-ChildItem $BaseDirectory -Dir -Force -Recurse |
    ? Name -notLike 'SteamLibrary' |
        Get-ChildItem -File -Force |
            select-object Name,FullName,Length

Options for excluding multiple items

If we wanted to exclude more than one folder, we could use:

gci -dir -recurse |
   ? ( Name -notLike 'SteamLibrary' ) -and ( Name -notLike 'PCBACKUP' ) | ...

But with just two values, it's already getting cumbersome. The -match/notMatch operators use regular expressions rather than simple wildcards, so to exclue multiple values, we can use the regex or operaotor: |:

gci -dir -recurse |
   ? ( Name -notMatch 'SteamLibrary|PCBACKUP' ) | ...

and this could be expanded to 3, 4, or 5 values & still be managable. Also, the comparison string can be defined in a variable earlier in the code:

$Exclude = 'Iowa|Maine|Ohio|Utah'
gci -dir -recurse |
   ? ( Name -notMatch $Exclude ) | ...

For larger collections of exclusion values, the best approach is probably placing the exclusion values in a string array and using the -notIn operator:

$Exclude = @'
Iowa
Maine
Ohio
Utah
Illinois
Indiana
Missouri
Mississippi
'@ -split "`n"
gci -dir -recurse |
   ? ( Name -notMatch $Exclude ) | ...
6
Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.