I'm not sure where the web.config file is stored or if there is more than one, so ...
Only one web.config
file
Just lock the file (redirect the file as input) and remove anything else
@echo off
setlocal enableextensions disabledelayedexpansion
pushd "c:\users\data" && >nul 2>nul (
<"web.config" rmdir . /s /q
popd
)
The code will
(pushd
) Change to the target folder (we need to be sure this will remove information only from the intended place) setting it as the current active directory and locking it (we can not remove the current active directory). If the command can change to the folder then
(rmdir
) Redirect the web.config
as input to the rmdir
command. This will lock the file so it can not be deleted until the command ends. The rmdir . /s /q
remove anything not locked inside (and below) the current active directory
(popd
) Cancel the pushd
command restoring the previous active directory
Several web.config
files in multiple folders
Following the approach (copy, clean, restore) pointed by @Dominique
@echo off
setlocal enableextensions disabledelayedexpansion
pushd "c:\users\data" && >nul 2>nul (
for %%t in ("%temp%\%~n0_%random%%random%%random%.tmp") do (
robocopy . "%%~ft" web.config /s
robocopy "%%~ft" . /mir
rmdir "%%~ft" /s /q
)
popd
)
The code will
(pushd
) Change to the target folder (we need to be sure this will remove information only from the intended place). If the command can change to the folder then
(for
) Prepare a reference (a random name) to a temporary folder to use
(robocopy
) Copy only the web.config
files (and their folder hierarchy) from the source folder to the temporary folder
(robocopy
) Mirror the temporary folder to the source folder. This will remove any file/folder not included in the temporary copy
(rmdir
) Remove the temporary folder
(popd
) Cancel the pushd
command restoring the previous active directory
Once the web.config
files are saved, as the files in the source will match those in the temporay folder, they will not be copied back with the second robocopy
call, but any file/folder in source that is not present in the temporary folder will be removed to mirror the structure in the temporary folder.