Powershell Deleting Files and Folders

Powershell Deleting Files and Folders

Here is a quick list of very useful File and Folder Deletion operation command-lets.

Completely delete a folder along with files and sub-folders in it forcefully:

Remove-Item “C:TempFldr” -Force -Recurse -ErrorAction SilentlyContinue

 

Completely delete a files and sub-folder under the folder but retain the folder.

Remove-Item “C:TempFldr*” -Force -Recurse -ErrorAction SilentlyContinue

 

Delete only the files under the folder but not sub-folders and files in it.

Remove-Item “C:TempFldr*.*” -Force -Recurse -ErrorAction SilentlyContinue

 

Delete ONLY files recursively under the folder and sub-folders while retaining the folder structure.

forfiles /p C:temp-new /s /c “cmd /c if @isdir==FALSE del @file”

 

Reference:

5 thoughts on “Powershell Deleting Files and Folders

    1. Hope below answers your query. You can straight away have this run in PS or you can even code a simple function in PS. Let me know if you are looking for any further help in this regard.

      Listing both Files and Folders:
      C:>forfiles /p C:temp-new /s

      “test”
      “test-1”
      “Tl-1.json”
      “Tl-2.json”
      “Tl-3.json”
      “Tl-4.json”
      “essay2009e.pdf”
      “info_note_1.pdf”
      “role_an.pdf”

      Listing ONLY Files:
      C:>forfiles /p C:temp-new /s /m *.*

      “Tl-1.json”
      “Tl-2.json”
      “Tl-3.json”
      “Tl-4.json”
      “essay2009e.pdf”
      “info_note_1.pdf”
      “role_an.pdf”

      Listing ONLY Folders
      C:>forfiles /p C:temp-new /s /c “cmd /c if @isdir==TRUE echo @file is a directory”

      “test” is a directory
      “test-1” is a directory

      Deleting ONLY Files
      C:>forfiles /p C:temp-new /s /c “cmd /c if @isdir==FALSE del @file”

      Checking if ANY Files left out
      C:>forfiles /p C:temp-new /s /m *.*
      ERROR: Files of type “*.*” not found.

      Checking Folders remain in-tact
      C:>forfiles /p C:temp-new /s

      “test”
      “test-1”

      C:>

  1. Can you delete all files & subfolders, excluding certain subfolders. Example: domain computer with 100’s of user profiles. Being able to delete all except default & public. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *