Deleting files with same filename but different extension

This topic contains 2 replies, has 2 voices, and was last updated by  J Kot93 2 years, 2 months ago.

  • Author
  • #27963

    J Kot93

    Hi, I am new to PS scripting and would like to do the following:

    I take RAW+JPEG images and put them into two folders, one having raw image files and the other having the corresponding JPEG images. The corresponding images have the same file name but with a different extension (e.g. …/RAW/IMG_0001.CR2 and …/JPEG/IMG_0001.JPG). I examine the images in the JPEG folder and delete all images I do not want to keep. What PS (version 2) command could I use to delete the corresponding images in the RAW folder? I am thinking a single Get-ChildItem should do it, but maybe a script would be better.

    Thanks... John

  • #27975

    Rob Simmers

    You pretty much spelled out what you would do, here is something to try:

    # Get all files in jpg and raw files in different objects 
    $jpgFiles = Get-ChildItem -Path C:\Temp\JPEG\* -Recurse | where { ! $_.PSIsContainer }
    $rawFiles = Get-ChildItem -Path C:\Temp\RAW\* -Recurse | where { ! $_.PSIsContainer }
    # Compare the directories using the basename (file name with no extension)
    # Where the file exists in raw, but not in jpg
    # for each file, remove it
    Compare-Object -ReferenceObject $jpgFiles -DifferenceObject $rawFiles -Property BaseName -PassThru | 
    Where{$_.SideIndicator -eq "=>"} |
    foreach{Remove-Item -Path $_.FullName -Force -WhatIf}

    Note that there is a -WhatIf on Remove-Item, so it will not actually perform a remove until you test it. In my test, I had 5 image files in RAW and had 3 in JPEG, so it would have done the following:

    What if: Performing the operation "Remove File" on target "C:\Temp\RAW\Image01.CR2".
    What if: Performing the operation "Remove File" on target "C:\Temp\RAW\Image03.CR2".
    What if: Performing the operation "Remove File" on target "C:\Temp\RAW\Image04.CR2".
  • #28038

    J Kot93

    Thanks Rob for your reply.

    I managed to pare down to one piped command:

    diff $(gci *.JPG) $(gci CR\*.CR2) -property BaseName | foreach {rm CR\$($_.BaseName).CR2 -Verbose -WhatIf}

    (excuse the use of aliases).
    Thanks again... John

You must be logged in to reply to this topic.