Search code examples
powershellfilteringpowershell-4.0get-childitem

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"}
  • Remove the name index.aspx from the returned item.
  • I want to filter out any file that starts with and underscore.
  • Exclude anything that contains /stocklist/ in its path.
  • Exclude anything that contains /assets/ in its path.
  • And exclude anything that contains .bk in its path.

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.


Solution

  • 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*_' }