This script remove files more than X size and notify log by Telegram.
Powershell script:
- set variables.
- run on Powershell.
can be used with task scheduler to keep specific folders clean
# First, we specify the details of the Telegram account and the chat ID
$botToken = Get-Content -Path Env:\botToken
$chatId = Get-Content -Path Env:\chatId
# Then, we define the path of the directory that we want to check, Size,Log Directory
$directory = "YOUR_PATH"
$sizeFile = 2GB #100MB
$directoryLOG = YOUR_PATH
# We get a list of files in the directory that are greater than size specify
$filesBig = Get-ChildItem $directory -Recurse | Where-Object { $_.Length -cge $sizeFile } | Select-Object Name,";",Directory,@{n='GB';e={"{0:N2}" -F ($_.length/ 1GB)}}
# If there are no files that meet the criteria, we end the execution of the script
if ($filesBig.Count -eq 0) {
Write-Host "No files larger than $($sizeFile/1GB)GB."
return
}
# If there are files that find the criteria, we generate the message that will be sent by Telegram
$message = "$(Get-Date -Format "yyyyMMdd_HH:mm:ss") ;"
foreach ($files in $filesBig) {
$message += "$($files.Name) ;$($files.GB)GB; $($files.Directory) ;files more than $($sizeFile/1GB)GB `n"
# Save LOG
Add-Content -Path $directoryLOG $message
# Remove items
Get-ChildItem $directory -Recurse | Where-Object { $_.Length -cge $sizeFile } | Remove-Item -Force
}
# Send the message via Telegram
$message = [System.Web.HttpUtility]::UrlEncode($message)
$uri = "https://api.telegram.org/bot$botToken/sendMessage?chat_id=$chatId&text=$message"
Invoke-WebRequest -Uri $ur
Thanks for read!
Top comments (0)