powershellrobocopycopy-itemwhere-object

How to delete a folder in the destination folder only if it exists in the source folder


Using Powershell, How can I delete folders in the destination folder only if they exist in the source folder?

For example I have the folder structure below and want to delete Folders1 2 and 3 before I copy them from the source folder. I have tried Robocopy with the /mir switch however this deletes folder4 as well

Source folder:  
  Folder1
  Folder2
  Folder3  

Destination folder:
  Folder1  
  Folder2
  Folder3
  Folder4  

Solution

  • Iterate over the folders in the source directory and use Test-Path to check whether they exist in the destination directory; if they exist, delete them:

    $srcDir = ".\source"
    $destDir = ".\dest"
    
    foreach($sd in Get-ChildItem -Directory $srcDir){
      $dd = "$destDir\$($sd)"
      if (Test-Path "$dd"){
        Remove-Item "$dd" -WhatIf
      }
    }
    

    (remove -WhatIf once you have tested this out).