Command to delete files in UNC path

Gowtham picture Gowtham · Feb 5, 2014 · Viewed 21.5k times · Source

Hi I tried below command to delete files in UNC path

set folder="\\SERVERNAME\Publish" 
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)

But I got error saying:

UNC paths are not supported. Defaulting to Windows Directory

Somehow I need to delete files that are residing in Server's shared path using batch command. Any help appreciated.

Answer

MC ND picture MC ND · Feb 5, 2014

edited 2015-09-16 - Original answer remains at the bottom

Code reformated to avoid removal of non desired folders if the mapping fails. Only if the pushd suceeds the removal is executed.

set "folder=\\SERVERNAME\Publish" 
pushd "%folder%" && (
    for /d %%i in (*) do rmdir "%%i" /s /q 
    popd
)

original answer:

set "folder=\\SERVERNAME\Publish" 
pushd "%folder%"
for /d %%i in (*) do rmdir "%%i" /s /q 
popd

pushd will create a drive mapping over the unc path and then change to it. Then, all the operations are over drive:\folders. At the end popd will remove the drive assignation.