Powershell script to delete particular type of file extension without removing the Folders

Loganathan R 71 Reputation points
2023-02-05T14:31:57+00:00

Hello All,

I have requirement to remove the particular type of files extension from the computer without removing the folders. The files are in various path of the system and i have planned to map the C:/ and also log need to be stored for what are all the files are getting deleted. Any advise or suggestion on this are highly appreciated.

Planned to use the SCCM to run the script to get it deleted on the remote machines.

Below are the scripts i have came across

Remove-Item -Recurse -Path C:\Delete-Testing* -exclude dontdelete.txt,foldertokeep

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,283 questions
Microsoft Configuration Manager
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
1,868 questions
0 comments No comments
{count} votes

Accepted answer
  1. AllenLiu-MSFT 38,406 Reputation points Microsoft Vendor
    2023-02-06T07:45:06.0233333+00:00

    Hi, @Loganathan R

    Thank you for posting in Microsoft Q&A forum.

    Please try the below script, it removes all the txt file under c:\temp, and log all the deleted files to the test.log.

    $logFile = 'c:\temp\test.log'
    
    $files = get-childitem -path C:\temp -file -recurse -include *.txt
    
    ($files).fullname >> $logFile
    
    $files | Remove-Item
    
    

    1


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Add comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. MotoX80 30,991 Reputation points
    2023-02-05T16:41:53.96+00:00

    Use Get-Childitem to identify the files that you wish to delete. Use include, not exclude.

    get-childitem -path C:\temp -file -recurse -include *.txt
    

    Then list off the files and first test with the WhatIf switch.

    $files = get-childitem -path C:\temp -file -recurse -include *.txt
    "Here are the file that will be deleted."
    ($files).fullname
    ""
    "Performing delete."
    $files | Remove-Item -whatif
    
    

    https://www.sapien.com/books_training/Windows-PowerShell-4

    0 comments No comments