Home > Software design >  Batch script to delete all the subfolders inside specific folder in all remote servers and output as
Batch script to delete all the subfolders inside specific folder in all remote servers and output as

Time:01-06

Here I am trying to execute a batch script which deletes subfolders under folder "updates" in all remote machines. List of servers are passed as input (serverlist.txt)

echo off
for /f %%l in (C:\deleteauto\delrem\serverlist.txt) do
if exist C:\updates goto sub
if not exist C:\updates goto nofile

:sub
del /f /q "C:\updates\*.*"
for /d %%d in ("C:\updates\*.*") do rmdir /s /q "%%d"
echo folder is deleted in %%l >>c:\finaloutput.txt

:nofile
echo No folders in %%l >>c:\final output.txt

Can someone please help in rectifying the errors. Script executed but outputs nothing.

CodePudding user response:

Try this code:

@echo off
for /f "tokens=*" %%l in (C:\deleteauto\delrem\serverlist.txt) do (
    if exist "\\%%l\C$\updates" (
        pushd "\\%%l\C$\updates"
        del /f /q "*."
        for /d %%d in ("*.") do rmdir /s /q "%%d"
        echo Folder is deleted on server: %%l>>finaloutput.txt
        popd
    ) else (
        echo Folder does not exist on server: %%l>>finaloutput.txt
    )
)

CodePudding user response:

Here's an example of how I may tackle the task:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "SvrLst=C:\deleteauto\delrem\serverlist.txt"

If Not Exist "%SvrLst%" GoTo :EOF
(For /F UseBackQ^ Delims^=^ EOL^= %%G In ("%SvrLst%"
    ) Do PushD "%%~G\C$\updates" 2>NUL && (
        RD /S /Q . 2>NUL
        Echo Instruction to empty directory applied on %%~G & PopD
    ) || Echo Directory path not found on %%~G) 1>"C:\finaloutput.txt"

You will note that I have not stated that the directory was emptied. Just because an instruction was applied, does not mean that it was successful at doing so. Unless you check that the \C$\updates directory is completely empty afterwards, you should not imply that it is.

CodePudding user response:

Errors were rectified by @Fire Fox , Thank you! Modified slightly & it worked as expected. Code:

@echo off
for /f "tokens=*" %%l in (C:\deleteauto\delrem\serverlist.txt) do (
    if exist "\\%%l\C$\updates" (
        pushd "\\%%l\C$\updates"
        del /f /q "\\%%l\C$\updates\*.*"
        for /d %%d in ("\\%%l\C$\updates\*.*") do rmdir /s /q "%%d"
        echo Folder is deleted on server: %%l>>C:\finaloutput.txt
        popd
    ) else (
        echo Folder does not exist on server: %%l>>C:\finaloutput.txt
    )
)
  • Related