Home > Software design >  Delete folder but exclude specific folder
Delete folder but exclude specific folder

Time:08-01

For student computers I need to cleanup the windows userprofile-folders (C:\Users*). But I need to keep the following folder( and do it with batch, no powershell-scripts possible, only single commands):

  • Administrator
  • All Users
  • Default
  • Default.lic
  • Default User
  • defaultuser0
  • Public
  • 40040
  • 40041

I tried this one, but it deleted all folder and didnt exclude anything:

if "%1" == "Administrator" goto End
if "%1" == "All Users" goto End
if "%1" == "Default" goto Ende
if "%1" == "Default.lic" goto End
if "%1" == "Default User" goto End
if "%1" == "defaultuser0" goto End
if "%1" == "Public" goto End
if "%1" == "40040" goto End
if "%1" == "40041" goto End
rmdir /S /Q "C:\Users\%1"
powershell "Remove-Item -Path \"HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-21*\" -Recurse"
:End

In my mind is the idea to do with something like an excludelist, but findstr didn't work out. The examples I found where all using only one variable etc. but is this case it should be something in the way:

if C:\Users\* is not C:\Users\*excluded-folder-variable* do rmdir /S /Q "C:\Users\%1"

CodePudding user response:

Try this:

@echo off
setlocal EnableDelayedExpansion

set "exclude=|Administrator|All Users|Default|Default.lic|Default User|defaultuser0|Public|40040|40041|"

cd "C:\Users"

for /D %%f in (*) do (
   if "!exclude:|%%~f|=!" equ "%exclude%" rmdir /S /Q "%%~f"
)

You have not shown where your %1 comes from, but you may insert the if "!exclude:... command in your code changing %%~f by %~1 and adjusting subdirectory as needed...

CodePudding user response:

If all the folders to exclude are in the Users folder, it's easiest to use the following code:

for /f "tokens=*" %%d in ('dir /b /ad "%HOMEDRIVE%\Users"') do call :REMOVE "%%d"
goto :EOF
:REMOVE
if /i "%~1" == "Administrator" goto :EOF
if /i "%~1" == "All Users" goto :EOF
if /i "%~1" == "Default" goto :EOF
if /i "%~1" == "Default.lic" goto :EOF
if /i "%~1" == "Default User" goto :EOF
if /i "%~1" == "defaulters0" goto :EOF
if /i "%~1" == "Public" goto :EOF
if /i "%~1" == "40040" goto :EOF
if /i "%~1" == "40041" goto :EOF
rd /s /q "%~1"

You can add or remove any folder you want in the same way.

  • Related