Batch script for deleting user specific App Data Folder

Mahesh Jaiswal 86 Reputation points
2021-08-23T17:43:00.987+00:00

I am new to scripting and not having that much knowledge about scripting.

I searching for the batch script that can be used for cache/temp files deletion from all users specific folders.

I have created below batch script by doing internet searches but it is not working as expected. It is working file till inputs and user name inputs but after that exits directly.

@Echo off

:A
cls
set /p menu="Do you want to delete Temp File ? (Y/N): "
if %menu%==Y goto Yes
if %menu%==y goto Yes
if %menu%==N goto No
if %menu%==n goto No

cls
set /p exit="Press any key to continue!... "
goto A

:Yes
set /p Username="Please insert user name : "
del /s /f /q C:\Users\%username%\AppData\Local\foldername\subfoldername
echo %Username%
exit

:No
cls
echo.
echo Okay, let's exit...
echo.
exit

Thanks

Windows for business Windows Client for IT Pros Networking Network connectivity and file sharing
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 36,291 Reputation points
    2021-08-24T01:49:50.153+00:00

    For starters, you need to use the RD (remove directory) command instead of del (delete). Temporarily add in a pause command so that the script stops and that you can see what error message it produces.

    :Yes
    set /p Username="Please insert user name : "
    echo %Username%
    rd /s /q C:\Users\%username%\AppData\Local\foldername\subfoldername
    pause
    exit
    

    If that works for you then great. Beyond that I would recommend using Powershell instead of .bat files. You will be much better positioned for future support tasks.

    One major flaw in your code is that do not have any error handling. You blindly issue a delete for a folder. Well, what if the user enters the wrong username? You don't test to see if the folder exists or if the delete was successful.

    I don't know what your programming background is, but it appears that you might benefit from taking some programming courses.


3 additional answers

Sort by: Most helpful
  1. MotoX80 36,291 Reputation points
    2021-08-24T13:23:47.233+00:00

    Powershell is a good place to start. Win10 comes with Powershell_ise.exe which is a decent development tool for writing and debugging scripts.

    To get started, here is a good reference/training document.

    https://www.sapien.com/books_training/Windows-PowerShell-4

    Some info on ISE.

    https://learn.microsoft.com/en-us/powershell/scripting/windows-powershell/ise/introducing-the-windows-powershell-ise?view=powershell-7.1

    MS documentation.

    https://learn.microsoft.com/en-us/powershell/scripting/how-to-use-docs?view=powershell-5.1

    Here is your script written in PS. Load it into Powershell_ise and play with it.

    cls  
    while ($true) {                        # infinite loop that we will break out of  
        $menu = Read-Host "Do you want to delete Temp File ? (Y/N): "  
        if ($menu -match "n") {       # we have a no  
            write-host "Okay, let's exit..."   
            start-sleep 5             # if we are running as a .ps1 file, delay a bit so that the user can see our message   
            break                     # break out of the while loop to finish   
        }   
        if ($menu -match "y") {       # we have a yes  
            $Username = Read-Host "Please insert user name : "  
            if ($Username -eq "") {                                   # validate inout  
                Write-Host "Username cannot be blank."  
                continue                                              # loop again   
            }  
            $TargetDir = "C:\Users\" + $username + "\AppData\Local\foldername\subfoldername"  
            write-host "Checking $TargetDir"  
            if (Test-Path $TargetDir) {                                # verify that the folder exists                        
                write-host "The folder exists, attempting delete...."  
                try {                                                                           # we want to handle errors   
                    Remove-Item -Path $TargetDir -Recurse -ErrorAction Stop                     # remove all subfolders too  
                    Write-Host "Success!"  
                }  
                catch {                                                                         # something didn't work   
                    Write-Host "Error!!! We crashed!!!"  
                    Write-Host $_.ErrorDetails.Message   
                }  
            } else {  
                write-host "That folder does not exist, try again...."   
            }           
            continue                  # loop again   
        }  
        Write-host "Input not recognized. Please make a valid choice."            # user did not enter y/n   
    }  
      
    

  2. Limitless Technology 39,916 Reputation points
    2021-08-25T07:39:12.433+00:00

    Hello,

    Thank you for your question.

    I would like to suggest you to use Powershell instead of Batch as Batch scripting is legacy and you may not able use all features of it

    Kindly have a look on below Powershell script to cleanup temp folders using PS from Microsoft DevBlogs.

    https://devblogs.microsoft.com/scripting/weekend-scripter-use-powershell-to-clean-out-temp-folders/

    If the reply was helpful, please don’t forget to upvote or accept as answer.

    Thanks,

    PRAKASH T

    0 comments No comments

  3. MotoX80 36,291 Reputation points
    2021-08-25T19:31:03.303+00:00

    can we add multiple folder path in below statement like this if we have multiple subfolder under main folder like as below

    I like to say that "programming is an art". By that I mean that; in a lot of cases, there are different ways to accomplish a given task with code. A lot depends on what you are trying to accomplish, how much error checking is required, do you need to interact with a user, etc.

    So yes, you could create an array of folder names and send that via a pipeline to a Remove-Item cmdlet, But given the starting point of your .bat file code, you might want to use an array and a function like this.

    $FolderList = @("\AppData\Local\foldername\subfoldername1",
                    "\AppData\Local\foldername\subfoldername2",
                    "\AppData\Local\foldername\subfoldername3")
    
    Function FolderKiller ($pThisFolder) {                           # the folder name is a positional parameter  
        write-host "Checking $pThisFolder"
        if (Test-Path $pThisFolder) {                                # verify that the folder exists                      
            write-host "The folder exists, attempting delete...."
            try {                                                                           # we want to handle errors 
                Remove-Item -Path $pThisFolder -Recurse -ErrorAction Stop                     # remove all subfolders too
                Write-Host "Success!"
            }
            catch {                                                                         # something didn't work 
                Write-Host "Error!!! We crashed!!!"
                Write-Host $_.ErrorDetails.Message 
            }
        } else {
            write-host "That folder does not exist, try again...." 
        }     
    }
    
    
    cls
    while ($true) {                        # infinite loop that we will break out of
        $menu = Read-Host "Do you want to delete Temp File ? (Y/N): "
        if ($menu -match "n") {       # we have a no
            write-host "Okay, let's exit..." 
            start-sleep 5             # if we are running as a .ps1 file, delay a bit so that the user can see our message 
            break                     # break out of the while loop to finish 
        } 
        if ($menu -match "y") {       # we have a yes
            $Username = Read-Host "Please insert user name : "
            if ($Username -eq "") {                                   # validate inout
                Write-Host "Username cannot be blank."
                continue                                              # loop again 
            }
            foreach ($fldr in $FolderList) {                           # we want to delete multiple folders for this user 
                $TargetDir = "C:\Users\" + $username + $fldr 
                FolderKiller $TargetDir                                # Call our delete function and pass it the name of the folder
            }    
        } else {
            Write-host "Input not recognized. Please make a valid choice."            # user did not enter y/n 
        }
    }
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.