How to Delete all files in a directory and also from Subfolders except one specific Subfolder and also keep the folder structure intact

Hi @Debojyoti_chanda,

Replying here to give people reading this thread another option to achieve this using PowerShell.

  1. Get all items in the root location with .xlsx format here the -Recurse option performs a recursive search
  2. Filter objects where the $_.FullName does not match (does not contain) archive in its path (-Quiet returns a boolean) ($_.FullName here is returns the full path to the file)
  3. Now we loop through each piped object and use the versatile Remove-Item method to delete files.
$FolderRootLocation = ""
Get-ChildItem -Path $FolderRootLocation -Recurse -Include '*.xlsx' |  
Where-Object { ($_.FullName | Select-String -NotMatch "archive" -Quiet) } | 
ForEach-Object{Remove-Item -Path $_.FullName}

If you wish to make this dynamic and integrate it with UiPath the script would be as shown below. If you have doubts on how to integrate it with UiPath, please read through this Tutorial :

Param{
    [Parameter(Mandatory=$true)] [string]$TargetFolderLocation,
    [Parameter(Mandatory=$true)] [string]$IgnoreFolderWithString,
    [Parameter(Mandatory=$true)] [string]$FileExtensionType
}

Get-ChildItem -Path $TargetFolderLocation -Recurse -Include (-join('*.',$FileExtensionType))|  
Where-Object { ($_.FullName | Select-String -NotMatch $IgnoreFolderWithString -Quiet) } | 
ForEach-Object{Remove-Item -Path $_.FullName}
1 Like