DEV Community

redhcp
redhcp

Posted on • Edited on

Powershell Delete files by Size & Notify Telegram Log

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
Enter fullscreen mode Exit fullscreen mode

Thanks for read!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 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