DEV Community

redhcp
redhcp

Posted on

Powershell - Delete files by Size & Telegram Notification

This script, you can delete files more than specific size and send notification by Telegram.

# First, we specify the details of the Telegram account and the chat ID

#Variables Region
$botToken = Get-Content -Path  Env:\botToken
$chatId =   Get-Content -Path  Env:\chatId 

$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 not 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 are files that find the criteria, 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 $uri 
Enter fullscreen mode Exit fullscreen mode

Note: you can schedule task for automate this script.

Thanks for read!

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

๐Ÿ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay