Muttly
Muttly

Reputation: 21

Windows Compare filenames and delete 1 version of the filename

I have several hundred folders where I will have multiple files called filename.ext but also another file called filename.ext.url

I need a way of checking if filename.pdf.url exists does filename.ext exist. If they both exist delete filename.ext.url

I can't just do a search and delete all *.url files as they will be needed if the normal file does not exist

I then need to repeat that in all subdirectories of a specific directory.

I don't mind its its a batch script, powershell script that does it or any other way really. I'm just stumped on how to do what I want.

Currently I'm doing it folder by folder, manually comparing file names, file size and file icon.

Upvotes: 1

Views: 110

Answers (3)

Robert Cotterman
Robert Cotterman

Reputation: 2268

foreach ($file in ls -Recurse c:\files\*.url) {
    if (ls -ErrorAction Ignore "$($file.PSParentPath)\$($file.basename)") {
        remove-item $file.fullname -whatif
    }
}

remove whatif when ready to delete. the basename removes the extension, so if they are all .ext.url then it will check if that file exists. It also removes the path, so we pull that as well.

an alternative way (that more matches what you're explaining) is something like

foreach ($file in ls -Recurse "c:\files\*.url") {
    ### replacing '.url$' means .url at the end of the line in Regex
    if (ls -ErrorAction Ignore ($file.FullName -replace '\.url$')) {
        remove-item $file.fullname -whatif
    }
}

Upvotes: 2

Magoo
Magoo

Reputation: 79982

for /r "startingdirectoryname" %b in (*.url) do if exist "%~dpnb" ECHO del "%b"

This is expected to be executed directly from the prompt. If the requirement is as a batch line, each % needs to be doubled (ie. %%).

This also assumes that the whatever.ext file is to be in the same directory as the whatever.ext.url file.

Note that the filenames that are to be deleted will merely be echoed to the console. To actually delete the files, remove the echo keyword.

Test against a test directory first!

[untested]

Upvotes: 2

James K
James K

Reputation: 4055

To check for "filename.ext", check for "filename.ext.", they are the same file.

In CMD.EXE, you can do "IF EXIST "filename.ext." CALL :DoIt

Upvotes: -1

Related Questions