How to exclude directory in Get-ChildItem results?

1.3k views Asked by At

My script is doing what I need it to do, but I would like to be able to exclude certain folders.

In this case, it would be \york\SedAwk\ and \york\_ROT\.

Now, if I only put one folder in the $exclude variable, it works as expected. It's when I put both (or more) that it excludes neither, and throws no errors either when running.

Here is the script:

param(
    [string]$pattern,
    [string]$path  
    ) 
$exclude = @('*\york\SedAwk\*','*\york\_ROT\*')
Get-ChildItem -path $path -Recurse -Filter *.html | 
    Where-Object{
        ForEach-Object {
            If (Get-Content $_.FullName | Select-String -Pattern "<h2>Stay Connected") {
                Select-String -InputObject (Get-Content $_.FullName | Out-String) -Pattern "(?sm)<main([\w\W]*)$pattern([\w\W]*)<h2>Stay Connected" -Quiet
            }
            ElseIf (Get-Content $_.FullName | Select-String -Pattern "<h2>Soyez branch") {
                Select-String -InputObject (Get-Content $_.FullName | Out-String) -Pattern "(?sm)<main([\w\W]*)$pattern([\w\W]*)<h2>Soyez branch" -Quiet
            }
            Else {
                Select-String -InputObject (Get-Content $_.FullName | Out-String) -Pattern "(?sm)<main([\w\W]*)$pattern([\w\W]*)<\/main>" -Quiet
            }
        }
    } |
    Select Fullname | ?{$_.FullName -notlike $exclude}

And here is how I run it:

.\FindStringContent.ps1 -pattern "list-unstyled" -path "w:\test\york" | Export-CSV "C:\Tools\exclude.csv"
1

There are 1 answers

2
Bluecakes On

I don't like using the -Exclude parameter because it's not file/folder specific, if you have a file and a folder that matches the string you're excluding they'll both be excluded.

When i'm excluding files i exclude them based on the FullName property which you could put in your ForEach to check if any of the files is in your $exclude variable:

param(
    [string]$pattern,
    [string]$path  
    ) 
$exclude = 'SedAwk','_ROT'
Get-ChildItem -path $path -Recurse -Filter *.html | 
    Where-Object{$_.FullName -notlike $exclude -and ForEach-Object {
        If ($exclude -notcontains $_.FullName) {
            If (Get-Content $_.FullName | Select-String -Pattern "<h2>Stay Connected") {
                Select-String -InputObject (Get-Content $_.FullName | Out-String) -Pattern "(?sm)<main([\w\W]*)$pattern([\w\W]*)<h2>Stay Connected" -Quiet
            }
            ElseIf (Get-Content $_.FullName | Select-String -Pattern "<h2>Soyez branch") {
                Select-String -InputObject (Get-Content $_.FullName | Out-String) -Pattern "(?sm)<main([\w\W]*)$pattern([\w\W]*)<h2>Soyez branch" -Quiet
            }
            Else {
                Select-String -InputObject (Get-Content $_.FullName | Out-String) -Pattern "(?sm)<main([\w\W]*)$pattern([\w\W]*)<\/main>" -Quiet
            }
        }
    }
} | Select Fullname

Included suggested changes by TheMadTechnician