1

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
SRP
  • 999
  • 4
  • 21
  • 39
  • Related: https://stackoverflow.com/q/15246602/7571258 | https://stackoverflow.com/q/61934452/7571258 | https://stackoverflow.com/questions/50744489/how-to-exclude-files-by-part-of-directory-path – zett42 Jun 20 '22 at 13:35

1 Answers1

3

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
Theo
  • 57,719
  • 8
  • 24
  • 41