Deleting multiple files from multiple computers not working as expected
Home › Forums › Scripting › PowerShell › Deleting multiple files from multiple computers not working as expected
- This topic has 10 replies, 3 voices, and was last updated 1 year, 8 months ago by
crocodile.
-
AuthorPosts
-
crocodileMemberMay 14, 2019 at 11:27 pm #617239I have this script that I have compiled from different scripts to get exactly what I need.
The filelist looks something like this:
D$\Test1\Test1\*
D$\Test2\Test1\*Now I want to delete the file in all of the subfolders of Test1 and Test2, but not actually delete any subfolders. At this stage I am specifying each subfolder in the filelist, but that could be problematic in the future, as I would have to constantly monitor the folders to see if there are any subfolders added and then add them to the filelist. Ideally I need to only specify the folder, the script needs to go through all subfolders and delete all files, but not subfolders. The file count is also not working as expected, either reporting 1 or 0, which I guess is counting the folder and not the files. Any help to improve this would be highly appreciated.
function Write-Log($string)
{
$outStr = “” + $Timestamp +” “+$string
Write-Output $outStr
}
$Timestamp = Get-Date -Format “yyyy-MM-ddTHH-mm-ss”
$filelist = Get-Content C:\support\scripts\filelist.txt
$computerlist = Get-Content C:\support\scripts\computerlist.txt
$Log = “c:\support\scripts\logs\Delete_Old_Files_$(Get-Date -Format ‘yyyyMMddhhmmss’).log”
Start-Transcript -path $Log -append -Force -NoClobber
Write-Log “———— Start of Log ————”
foreach ($file in $filelist) {
foreach ($computer in $computerlist){
Write-Log “Analysing $computer”
$newfilepath = Join-Path “\\$computer\” “$file”
if (test-path $newfilepath) {
Write-Log “$newfilepath folder exists”
try
{
Remove-Item $newfilepath -Recurse -force -ErrorAction Stop | Where-Object { -not ($_.psiscontainer) }
}
catch
{
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Send-MailMessage -From [email protected]@aaa.com -To [email protected] -Subject “Old Files Delete Failed!” -SmtpServer bla.com -Body “The error message is: ‘$ErrorMessage'”
Break
}
Write-Log “$newfilepath files deleted”
} else {
Write-Log “Path $newfilepath no files to delete”
}
# output statistics
Write-Output “**********************”
#Write-Output “Number of old files deleted: $($_.Count)”
Write-Log “————- End of Log ————-”
}
}
Stop-Transcript
-
This topic was modified 1 year, 8 months ago by
crocodile.
-
This topic was modified 1 year, 8 months ago by
-
AuthorPosts
You must be logged in to reply to this topic.