1

I'm trying to remove application logs from shared drive for periodically,

ForFiles /p "\\netapp-1\Transfers\Logs\QA" /s /d -15 /c "cmd /c del @file"

The above command is working when the path is my local drive, but its not working for shared drive, any help will be highly appreciated.

Cheers!

Dominique
  • 16,450
  • 15
  • 56
  • 112
King_Fisher
  • 1,171
  • 8
  • 21
  • 51
  • 4
    `pushd "\\netapp-1\Transfers\Logs\QA" && (ForFiles /s /d -15 /c "cmd /c del @file" & popd)` – sst Jul 30 '18 at 08:16
  • 3
    UNC paths are not well supported by `cmd`, so use `net use Z: "\\netapp-1\Transfers\Logs\QA"`, then do `forfiles /S /P "Z:\." /D -15 /C "cmd /C if @isdir==FALSE del @path"`, then do `net use Z: /DELETE`... – aschipfl Jul 30 '18 at 08:18

1 Answers1

5

ForFiles.exe does not support UNC paths as the starting directory to start searching from, thus you have to temporarily map a <Drive Letter>: to the network path.

And the most convenient way to this, is to use pushd/popd command pair to do the MAP/UNMAP automatically, without concerning ourselves with which drive letters are currently available for mapping.

pushd "\\netapp-1\Transfers\Logs\QA" && (ForFiles /s /d -15 /c "cmd /c if @isdir==FALSE del @path" & popd)

In a batch file the above can be written in multiple lines for better readability

pushd "\\netapp-1\Transfers\Logs\QA" && (
    ForFiles /s /d -15 /c "cmd /c if @isdir==FALSE del @path"
    popd
)

And there are two flaws in your ForFiles command sample that I didn't pay attention to when I was providing the preliminary solution in the comments section, which has been addresses by aschipfl in the comments:

  • The directories should be excluded from processing by if @isdir==FALSE to not pass them to the del command

  • The @path variable should be used instead of @file, to pass the fully qualified paths to the del command otherwise it can not files the in the subdirectories to delete them.


Important Note:

Note the usage of conditional operator - double ampersands && (which is different from single & - command separator) after the pushd command. It guarantees ForFiles(and popd) will be executed If and only If, the prior pushd command was successful.

It protects the files in current directory from being accidentally deleted in case the pushd command fails to map the network path or fails to switch the directory to that path.
So take it seriously.

sst
  • 1,443
  • 1
  • 12
  • 15