How to exclude some directories and files from deliting in Delete Files task

Viewed 2382

I want to delete all files from $(Build.ArtifactStagingDirectory) (it is so called "a" folder in the appropriate build agent's folder, click here to read more about predefined variables in azure pipelines). I also know that Delete Files task uses the minimatch patterns.

The inner structure of my $(Build.ArtifactStagingDirectory):

a
|--Client
|       |--ImportantFolder
|       |                |--FileNumber1
|       |                |--....(Many other files here)
|       |                |--FileNumberN
|       |--OtherJunkFolder
|       |--OtherFile
|--JunkFolder

So, the folder a has two subfolders (Client and JunkFolder), the Client folder has one folder named ImportantFolder, one folder named OtherJunkFolder and one file named OtherFile. ImportantFolder has the many files with different names and extensions.

How can I delete all folders and files from the folder a except those in folders Client/ImportantFolders? In other words: I want to do something like this:

**
!Client/ImportantFolder/**

But this pattern delete everything from the folder a. I also tried

**
!(Client/**)

and just

**
!(Client)

Both didn't work.

2 Answers

Try without ** and only with !(Client), it will remove the JunkFolder except the Client folder.

You can do Client/ImportantFolder, I don't know why, I guess because the delete look on the a folder and not deeper.

After testing, pattern !(Client) works. But it also keeps the OtherJunkFolder and OtherFile in folder Client.

Pattern !(Client/ImportantFolder) does not work.

As workaround you can use a script task to delete all folders and files from the folder except those in folders Client/ImportantFolders. Please check below powershell script in a powershell task.

Get-ChildItem "$(build.artifactstagingdirectory)" | where { $_.Name -inotmatch "Client" } | Remove-Item -Recurse
Get-ChildItem "$(build.artifactstagingdirectory)/Client" | where { $_.Name -inotmatch "ImportantFolder" } | Remove-Item -Recurse

Another possible workaround is the use a copy file task to copy the folder Client/ImportantFolder to a new folder. For below example, folder Client/ImportantFolder will be copied to a new folder $(Agent.BuildDirectory)/a1 . And then point the following tasks to this new folder.

enter image description here

If your intention is to only include folder Client/ImportantFolder in your artifacts to be published in the following publish build artifacts task. The easiest way is to point Path to publish to folder Client/ImportantFolder. Then the artifacts published will only have folder Client/ImportantFolder. Check below example:

enter image description here

Related