Strontium_99
Strontium_99

Reputation: 1803

Excluding multiple items from Get-ChildItem using Powershell version 4

I'm iterating through a directory tree but trying to filter out a number of things.

This is my cobbled together code;

Get-ChildItem -Path $pathName -recurse -Filter index.aspx* -Exclude */stocklist/* | ? {$_.fullname -NotMatch "\\\s*_"} | Where {$_.FullName -notlike "*\assets\*" -or $_.FullName -notlike ".bk"}

This is working for everything but for the .bk in it's path. I'm pretty sure it's a syntax error on my part.

Thanks in advance.

Upvotes: 0

Views: 610

Answers (1)

Theo
Theo

Reputation: 61028

You can create a regex string and use -notmatch on the file's .DirectoryName property in a Where-Object clause to exclude the files you don't need:

$excludes = '/stocklist/', '/assets/', '.bk'
# create a regex of the folders to exclude
# each folder will be Regex Escaped and joined together with the OR symbol '|'
$notThese = ($excludes | ForEach-Object { [Regex]::Escape($_) }) -join '|'

Get-ChildItem -Path $pathName -Filter 'index.aspx*' -File -Recurse |
Where-Object{ $_.DirectoryName -notmatch $notThese -and $_.Name -notmatch '^\s*_' }

Upvotes: 1

Related Questions