Search code examples
powershellget-childitempowershell-5.1

How to delete files from multiple folders excluding couple of folders?


We have a situation where the cp.exe and cp.dll are getting copied in build artifacts of all the folders and we want them only to be part of PS.Manager.Service and PS.A.Service folder/Artifacts.

From rest all the folders both the cp.exe and its cp.dll must be deleted. I tried doing that with the below script but It is not working. I am not sure what am I missing here.

Any suggestions would really help.

Thanks.

$SourceDirectory = "e:\cache\Agent03\2\s"
$EXcludeManagerFolder = "e:\cache\Agent03\2\s\PS.Manager.Service"
$EXcludeAFolder = "e:\cache\Agent03\2\s\PS.A.Service"

gci -path "$SourceDirectory" -Include "cp.exe, cp.dll" -Exclude "$EXcludeManagerFolder","$EXcludeAFolder " -Recurse -Force | Remove-Item -Recurse -Force

Solution

  • As zett42 already commented, Include, Exclude (and also Filter) only work on the objects Name, not the full path.

    The easiest way is to create a regex string with the folders you need to exclude so you can match (or -notmatch in this case)

    $SourceDirectory = "e:\cache\Agent03\2\s"
    # create a regex of the files and/or folders to exclude
    $exclude = 'PS.Manager.Service', 'PS.A.Service'  # foldernames to exclude
    # each item will be Regex Escaped and joined together with the OR symbol '|'
    $notThese = ($exclude | ForEach-Object { [Regex]::Escape($_) }) -join '|'
    
    (Get-ChildItem -Path $SourceDirectory -Include 'cp.exe', 'cp.dll' -File -Recurse).FullName |
        Where-Object { $_ -notmatch $notThese } |
        Remove-Item -Force