Search code examples
filebatch-filedelete-filedelete-directory

Batch file to delete files from users on network


I want the batch file to ask for Serial number and username and delete two specific folders from users profile. I made this but it seems to want to delete *.* from folder I am running it from.

@echo off

set /p serial="Enter Serial: "

set /p username="Enter Username: "

del *.* \\%serial%\C$\users\%username%\appdata\roaming\Microsoft\Windows\Recent\AutomaticDestinations
del *.* 
\\%serial%\C$\users\%username%\appdata\roaming\Microsoft\Windows\Recent\CustomDestinations
pause

Solution

  • Try next approach with basic checking all user's input:

    @ECHO OFF
    SETLOCAL EnableExtensions
    
    :inputServer
    set "serial="
    set /p "serial=Enter Serial: "
    if not defined serial goto :endlocal
    pushd "\\%serial%\C$\"
    if errorlevel 1 (
      echo wrong server name "\\%serial%"
      goto :inputServer
    )
    
    :inputUser
    set "_username="
    set /p "_username=Enter Username: "
    if not defined _username goto :endstack
    cd "\users\%_username%\appdata\roaming\Microsoft\Windows\Recent"
    if errorlevel 1 (
      echo wrong user name "%_username%" or path
      echo "\\%serial%\C$\users\%_username%\appdata\roaming\Microsoft\Windows\Recent"
      goto :inputUser
    )
    
    dir AutomaticDestinations\*.*
    dir CustomDestinations\*.*
    
    :endstack
    popd
    
    :endlocal
    pause
    

    Replace dir with del /Q no sooner than debugged.

    Resource for PUSHD - POPD pair:

    When a UNC path is specified, PUSHD will create a temporary drive map and will then use that new drive. The temporary drive letters are allocated in reverse alphabetical order, so if Z: is free it will be used first.