I'm not sure if this is what you want, but give it a try:
# Path of New file to replace with
$NewFile = "$PSscriptRoot\log4j-core-2.17.1.jar"
$LogFile = "$PSscriptRoot\Log.txt"
# Default Path to copy files over
$destination = "c:\"
# Find path of log4j...jar files
$found = Get-ChildItem c:\ -Filter "log4j-core*.jar" -Recurse -ErrorAction SilentlyContinue
# What happens if both C: and D: contain the file? Should D: be excluded ot combinded with results from C:????
if (!$found) {
$found = Get-ChildItem D:\ -Filter "log4j-core*.jar" -Recurse -ErrorAction SilentlyContinue
}
if ($found) {
foreach ($f in $found) {
$destination = Split-Path $f.FullName -Parent
"Deleting vulnerable .jar files found in $destination" | Add-Content $LogFile
try {
$DeleteFile = $f.FullName
if ($DeleteFile -ne $NewFile) {
Remove-Item $DeleteFile -Force
"SUCCESS: Successfully deleted files" | Add-Content $LogFile
}
else {
"NOACTION: $NewFile was found and ignored" | Add-Content $LogFile
}
}
catch {
"ERROR: Failed to delete files [$($Error[0].Exception.Message)]" | Add-Content $LogFile
}
}
}
else {
"Vulnerable log4j .jar files Not Found" | Add-Content $LogFile
}
"Copying over new file to $destination" | Add-Content $LogFile
try {
Copy-Item $NewFile $destination
"SUCCESS: Successfully Copied New File to $destination" | Add-Content $LogFile
}
catch {
"ERROR: Failed to copy New File in $destination" | Add-Content $LogFile
}