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!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs