如何用RMDIR清理C:\Users目录并保留Public和Default文件夹
Batch Script to Keep Only Specific Folders in C:\Users
Hey there! Let's get that cleanup script sorted for you. Since you need to repeatedly clear out C:\Users (keeping only Public and Default), here's a safe, fully functional batch script that does exactly that—plus I'll break down each part so you understand how it works.
Complete Script
@Echo off color F :: Define the directory we're cleaning up set "targetDir=C:\Users" :: List of folders we want to KEEP (separate with spaces if adding more later) set "keepFolders=Public Default" :Choice Echo. Echo ⚠️ WARNING: This will delete ALL folders in %targetDir% EXCEPT: %keepFolders% Echo. set /p "confirm=Type 'YES' to proceed, or anything else to cancel: " if /i not "%confirm%"=="YES" goto :Exit :: Enable delayed expansion to handle folder names with spaces setlocal enabledelayedexpansion :: Loop through every folder in the target directory for /d %%d in ("%targetDir%\*") do ( set "folderName=%%~nxd" :: Check if the current folder is in our keep list echo %keepFolders% | findstr /i /c:"!folderName!" >nul if errorlevel 1 ( :: Folder isn't in the keep list — delete it echo Deleting folder: "%%d" rmdir /s /q "%%d" ) else ( :: Folder is in the keep list — skip it echo Keeping folder: "%%d" ) ) endlocal Echo. Echo ✅ Cleanup completed! pause :Exit Echo Operation cancelled. pause
Key Details & Safety Notes
- Confirmation Prompt: The script asks for explicit "YES" input before deleting anything, so you won't accidentally run it and lose data.
- Delayed Expansion: Handles folder names with spaces (like "John Doe") correctly, which is common in
C:\Users. - Admin Rights: You need to run this script as an Administrator—some user folders in
C:\Usersrequire elevated permissions to delete. - Test First: Before running for real, replace
rmdir /s /q "%%d"withecho Would delete: "%%d"to preview which folders would be removed (no actual deletion happens). - Backup Critical Data: Double-check that no important files are stored in the folders you're deleting—this script removes folders and all their contents permanently.
内容的提问来源于stack exchange,提问作者Oliver Jeffries
相关产品推荐
相关产品推荐

