Any batchfile / Powershell gurus about?

Soldato
Joined
21 Jun 2004
Posts
2,790
Location
Berkshire
I've got an issue at work which we need some kind of script for, I could code something up in seconds for Linux/Unix but I've always found scripting on Windows a pain in the backside.

Let's say I have a directory full of files with two different extensions, e.g. 123.abc and 123.def

I need to remove all of the *.def files from the directory, but they can only be deleted if there is a matching *.abc file with the same filename

Does anyone know how this can be achieved with a script? There are thousands of files in this directory so definatley not something which can be done by hand!

Thanks
 
I like using TCC/LE (freeware) for this sort of thing - I'm sure it's doable with cmd.exe and certainly with Powershell, but with TCC it could hardly be easier:

for %a in ("*.abc") do del %@name[%a].def

Ancient folks like me who look back on 4DOS with teary-eyed nostalgia will find it very familiar. :)
 
Last edited:
I would run this, actually checks if the file exists before trying to remove it, and also tells you if no matching file is found.

Remove the "-WhatIf" from "Remove-Item $TestPath -WhatIf" below once testing has been completed and you are happy with it. PowerShell of course:

Code:
$Dir = "C:\Temp"
$Files = gci $Dir -Filter "*.abc"

foreach ($File in $Files)
{
	Write-Host $File.FullName -ForeGroundColor "Yellow"
	
	$TestPath = "$($File.Directory)\$($File.BaseName).def"
	
	if (Test-Path $TestPath)
	{
		#Matching .def file exists
		Remove-Item $TestPath -WhatIf
	}
	else
	{
		#Matching .def file does not exist
		Write-Host "No matching .def file found for $($File.FullName)"
	}
}
 
Last edited:
Back
Top Bottom