Search code examples
batch-fileforfiles

Is there a way to perform a negative search mask to forfiles?


I know how to utilize search masks in the forfiles command to target files of a particular extension, but I am working with a case where I want to avoid a particular extension and catch everything else.

Is there an easy way to achieve this with the forfiles command or will I need to write a custom for loop to handle this process? I am not looking to run a command like below which would force me to define my search masks before hand.

for %G in (.txt, .edi, .csv) do forfiles -p "C:abc\del" -s -m *%G -d -10 -c "cmd /c echo @path"

My use case is removing all files that are not encrypted from a directory recursively based on a single extension. This would be my negative value.


Solution

  • As per @Compo's comments to my question, an approach to applying a negative search mask to the forfiles command would be to add a filter to the cmd implementation after the fact like so:

    forfiles /P %localDir% /S /M *.* /C "cmd /c if not @EXT == %ignoredExtension% echo @PATH

    However, @Compo raised a valid concern that this implementation would cause a new cmd.exe instance to be opened for every file found. In instances where the file count is fixed or known to be constant this may be a decent approach, but a more efficient alternative that is able to be scaled would be to create a for loop manually that applies this filter at the for loop instance before making the call to the do operations like so:

    For /F "Delims=" %%G In ('dir /A-D^|FindStr /VE %ignoredExtensions%')Do @echo %%G