Failed to remove directory message

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Ape
Posts: 14
Joined: 05 Sep 2017, 07:55

Failed to remove directory message

17 May 2024, 16:54

My code:

Code: Select all

; AutoHotkey Script to Delete All Empty Folders and Subfolders in O:/Test

DeleteEmptyFolders(DirPath) {
    ; Get a list of all directories within the specified directory
    Loop, Files, %DirPath%\*, D
    {
        ; Recursively call the function on each subdirectory
        DeleteEmptyFolders(A_LoopFileFullPath)
    }
    
    ; Check if the directory is empty
    DirIsEmpty := true
    Loop, Files, %DirPath%\*, DR
    {
        ; If any file or directory is found, the directory is not empty
        DirIsEmpty := false
        break
    }
    
    ; If the directory is empty, delete it
    if (DirIsEmpty) {
        FileRemoveDir, %DirPath%
        if ErrorLevel
            MsgBox, 16, Error, Failed to remove directory: %DirPath%
    }
}

; Set the path to the directory you want to clean
TargetDir := "O:/Test"

; Ensure the target directory exists
if FileExist(TargetDir)
{
    ; Call the function to delete empty folders
    DeleteEmptyFolders(TargetDir)
    MsgBox, 64, Complete, Empty folders in %TargetDir% have been deleted.
}
else
{
    MsgBox, 16, Error, The directory %TargetDir% does not exist.
}
The error message:

Image

Does anyone know why this message happens and how to prevent it? The script works as intended.


[Mod action: Topic moved from "Ask for Help (v2)" since this is v1 code.]
User avatar
mikeyww
Posts: 27366
Joined: 09 Sep 2014, 18:38

Re: Failed to remove directory message

17 May 2024, 22:23

General reasons may include the following.
  1. Wrong path was specified.
  2. Script cannot access the directory due to wrong privileges.
  3. Directory does not exist.
  4. Directory is in use.
  5. Directory is not empty.
Mode "DR" does not include any files. You can verify this very quickly if you examine what happens in your loop.

Code: Select all

#Requires AutoHotkey v1.1.33.11
Loop Files, C:\Windows\System32\*.*, DR
 out .= A_LoopFilePath "`n"
MsgBox % Clipboard := Trim(out, "`n")
The documentation explains this well.
Mode:
If blank or omitted, only files are included and subdirectories are not recursed into. Otherwise, specify one or more of the following letters:

D = Include directories (folders).
F = Include files. If both F and D are omitted, files are included but not folders.
R = Recurse into subdirectories (subfolders). If R is omitted, files and folders in subfolders are not included.
Source: Loop (files & folders) - Syntax & Usage | AutoHotkey v1
If all files reside in the base directory, then DirIsEmpty will be falsely true.

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Bing [Bot], peter_ahk and 93 guests