[英]Batch Script doesn't delete the contents of the Temp folder with user input
@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
。 我也不會刪除整個臨時文件夾並重新創建,只需將其清除:
@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.