Search code examples
powershellbatch-filetemp

Doing same task in Batch instead of PowerShell: iterate all users and find %temp% folder to delete files inside


I have a powershell script that works as such: it deletes any files or folders within C:\users\%user1,2,3...etc%\temp. It goes through each user in users folder and finds if it has a temp folder then deletes stuff inside.

I need to know whats the best way to have this be done in Batch to avoid compatibility issues?

$users = Get-ChildItem C:\Users
foreach ($user in $users){
$folder = "$($user.fullname)\AppData\Local\temp"
   If (Test-Path $folder) {
     Get-ChildItem -Path $folder -Include * | remove-Item -recurse 
   }
}

Solution

  • You can do the following in a batch file to loop through C:\USERS and remove items in the TEMP folder:

    for /d %%F in (c:\users\*) do del "%%F\appdata\local\temp\*" /s /q
    

    If you run this at a command line, use just one percent sign, when using it a batch file, use two percent signs.

    This command loops over all directories in C:\USERS, and then runs a DEL against the AppData\Local\Temp folder, using silent and recursive parameters. This assumes that your user profiles are stored in C:\USERS, if you have reason to need to look for profiles everywhere, you'll want to adjust your batch file to find the profile paths from the registry first.

    As with all code you find online, test before running in production.