如何从命令行删除系统驱动器中的所有文件夹

时间:2011-09-17 09:46:43

标签: windows batch-file cmd

我正在尝试编写一个批处理脚本,删除系统驱动器中的所有文件夹和文件(系统文件夹,文件除外),但我卡在文件夹位上。这是针对Windows XP无人值守安装磁盘,我集成的其中一个更新在C:\驱动器上创建了一个随机文件夹,由于名称是随机的,我无法使用该脚本删除。这就是我到目前为止所得到的:

@echo off
color  17
echo del-test
echo.

echo Hiding foders we want to keep
if exist "%systemdrive%\AUTOEXEC.BAT"           attrib +h "%systemdrive%\AUTOEXEC.BAT"
if exist "%systemdrive%\CONFIG.SYS"             attrib +h "%systemdrive%\CONFIG.SYS"
if exist "%systemdrive%\Documents and Settings" attrib +h "%systemdrive%\Documents and Settings"
if exist "%systemdrive%\Program Files"          attrib +h "%systemdrive%\Program Files"
if exist "%systemdrive%\Sysprep"                attrib +h "%systemdrive%\Sysprep"
if exist "%systemdrive%\temp"                   attrib +h "%systemdrive%\temp"
if exist "%systemdrive%\WINDOWS"                attrib +h "%systemdrive%\WINDOWS"
echo Done!
echo.

echo Deleting everything that isn't hidden on the system drive
del /q  %systemdrive%\*.*
dir /b c:| rd
echo Done!
echo.

echo Unhiding Folders
if exist "%systemdrive%\AUTOEXEC.BAT"            attrib -h "%systemdrive%\AUTOEXEC.BAT"
if exist "%systemdrive%\CONFIG.SYS"              attrib -h "%systemdrive%\CONFIG.SYS"
if exist "%systemdrive%\Documents and Settings"  attrib -h "%systemdrive%\Documents and Settings"
if exist "%systemdrive%\Program Files"           attrib -h "%systemdrive%\Program Files"
if exist "%systemdrive%\Sysprep"                 attrib -h "%systemdrive%\Sysprep"
if exist "%systemdrive%\temp"                    attrib -h "%systemdrive%\temp"
if exist "%systemdrive%\WINDOWS"                 attrib -h "%systemdrive%\WINDOWS"
echo Done!
echo.
>nul pause

顺便说一下,我只需要删除一个文件夹。感谢。

2 个答案:

答案 0 :(得分:1)

deltree /y yourDirectory

del /s /f yourDirectory && rd /s yourDirectory 

Source

答案 1 :(得分:1)

这是另一个想法。基本上,您遍历%SYSTEMDRIVE%根目录中的所有文件/文件夹并使用IF语句来保护已知文件/文件夹。这只是一个示例,实际上并没有删除任何内容,您需要修改ECHO ** Deleting %%i行。这已经过测试,但不是很严重......请在实际删除之前进行测试。

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

FOR /F "usebackq delims==" %%i IN (`DIR %SYSTEMDRIVE%\ /b`) DO (
  IF /I "%%i" EQU "Program Files" SET DO_NOT_DELETE=Y
  IF /I "%%i" EQU "Sysprep" SET DO_NOT_DELETE=Y
  IF /I "%%i" EQU "Temp" SET DO_NOT_DELETE=Y
  IF /I "%%i" EQU "Windows" SET DO_NOT_DELETE=Y
  IF /I "%%i" EQU "junkfile.txt" SET DO_NOT_DELETE=Y
  IF !DO_NOT_DELETE! EQU Y (
    ECHO NOT deleting %%i
  ) ELSE (
    ECHO ** Deleting %%i **
  )
  SET DO_NOT_DELETE=
)