如何解决批处理脚本不会通过用户输入删除Temp文件夹的内容
@echo off
SET dir=%temp%
SET /p choice= Are you sure you want to delete your Temp Folder's contents? [y/n]
IF /I "%choice%"=="y" (
rmdir /s /Q %dir%
mkdir %dir%
Title Deleted Temp's contents
echo Deleted Temp's contents
timeout 2 > nul
exit
)
IF /I "%choice%"=="n" (
exit
) ELSE (exit)
我想自动删除Temp文件夹。 我正在Windows 10 2004版上运行此批处理脚本
解决方法
改为使用choice
,默认选项为Y/N
。我也不会删除整个temp文件夹并重新创建,只是将其清除:
@echo off
choice /m "Are you sure you want to delete your Temp Folder's contents?"
if errorlevel 2 goto :eof
for /D %%i in ("%temp%\*") do rd "%%i" /S /Q
del "%temp%\*" /S /Q
Title Deleted Temp's contents
echo Deleted Temp's contents
timeout 2 > nul
,
Windows无法删除当前工作目录所在的目录,因此清空目录的最佳方法是在尝试删除它之前将其设置为当前目录。这实际上将删除所有允许的内容,而无需触碰目录本身。 (注意:可能不会删除所有内容,仅那些未锁定/正在使用的内容以及您具有足够删除权限的内容)。
@Echo Off
SetLocal EnableExtensions
Rem If the directory to empty,has no file content,end the script.
"%__APPDIR__%where.exe" /Q /R "%TEMP%" * || (
Echo %TEMP% has no file content.
Echo Exiting . . .
"%__APPDIR__%timeout.exe" /T 3 /NoBreak 1> NUL
GoTo :EOF
)
Rem If the running script is in within,the directory to empty,end it.
SetLocal EnableDelayedExpansion
If /I Not "!__CD__:%TEMP%=!" == "%__CD__%" (
Echo Cannot empty %TEMP% because this script is located within it.
Echo Please move %~f0 to another location and try again.
Echo Press any key to exit . . .
"%__APPDIR__%timeout.exe" /T -1 1> NUL
GoTo :EOF
)
EndLocal
Rem Make the directory to empty,the current working directory.
Rem If the directory to empty,cannot be found,end the script.
PushD "%TEMP%" 2> NUL || (
Echo The directory assigned to %%TEMP%% cannot be found.
Echo Exiting . . .
"%__APPDIR__%timeout.exe" /T 3 /NoBreak 1> NUL
GoTo :EOF
)
Rem If the end user answers N,or n,end the script.
"%__APPDIR__%choice.exe" /M "Are you sure you want to empty your Temp directory"
If ErrorLevel 2 (
Echo Exiting . . .
"%__APPDIR__%timeout.exe" /T 3 /NoBreak 1> NUL
GoTo :EOF
)
Rem Empty permissible content from the current directory.
RD /S /Q . 2> NUL
Title Cleaned %CD%.
Echo Emptied permissible content from %CD%
Rem Make the previously current directory,current again.
PopD
Echo Press any key to exit . . .
"%__APPDIR__%timeout.exe" /T -1 1> NUL
GoTo :EOF
上面的代码可能比其他答案具有更多的内容,但是它显示了在创建脚本时应尝试遵循的逻辑顺序,尤其是那些删除文件和目录内容的脚本。
如果您不想在代码中考虑周全的结构,则可以这样做:
@CD /D "%TEMP%" 2>NUL||Exit /B
@"%__APPDIR__%choice.exe" /M "Are you sure you want to empty your Temp directory"
@If ErrorLevel 2 Exit /B
@RD /S /Q . 2>NUL
@Title Cleaned %CD%.
@Echo Emptied permissible content from %CD%
@"%__APPDIR__%timeout.exe" /T 2 1>NUL
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。