Search code examples
powershellshellterminalcommandwindows-subsystem-for-linux

Remove-Item does not delete folder


I need to delete a folder, but I get error can't remove because directory is not empty

I used this command :

Remove-Item \\wsl.localhost\Debian\home\my_folder_to_delete -Recurse -Force

How can I force this delete ?

PS: I use powerShell on windows 11

Thank you very much


Solution

  • From this answer, it's likely that the directory (or some file within it) is still being accessed by WSL.

    Important: For all answers below, please make sure that the directory does not include any critical files or symlinks to critical directories, as you'll be recursively removing everything in there.

    Option 1: Getting Windows PowerShell to do it

    Not recommended, but simply to demonstrate the problem and how to resolve it. For the proper way to do this, see Option 2.

    • Exit any WSL shell that you may have running

    • From PowerShell:

      wsl --shutdown
      

    That should release in "in-use" files.

    • Try the Remove-Item command again.

    Option 2: The Linux way

    From the comments suggesting doing this from the Linux shell:

    Do you know how can I use the Linux shell? I'm a beginner in this kind of things

    Well, there's nothing wrong with being a beginner (we all were at one point), but keep in mind that WSL is Linux in most ways. Understanding some "Linux basics" will be pretty necessary to finding your way around WSL. Side-note -- I'm considering doing a YouTube series on learning Linux with WSL. Keep an eye on my Profile if interested, and let me know in a comment if this would be interesting to you.

    \\wsl.localhost\Debian\home\my_folder_to_delete

    That translates to /home/my_folder_to_delete inside Debian. With that in mind, it's an odd directory to have created or want to delete. Just make sure you aren't removing your home directory, as that will cause issues.

    But to remove it (most safely):

    cd /home
    [ ! -L my_folder_to_delete] && rm -rf --one-file-system my_folder_to_delete
    

    Normally, in Linux, a simply rm -rf my_folder_to_delete would be sufficient, but this is a bit of my paranoid, over-protective version of the command to avoid something like this from happening.

    Note that if you created the directory as sudo or root, you may have to use the following:

    cd /home
    [ ! -L my_folder_to_delete] && sudo rm -rf --one-file-system my_folder_to_delete
    

    Option 3: The Linux + PowerShell way

    It's possible to use the Linux version of PowerShell inside Debian. See here for installation instructions. You can even set your user shell to PowerShell using the chsh command.

    I honestly can't decide whether this is a good or bad idea for a Linux newbie, though.