PowerShell: sending messages to Telegram.

In this article, we will show how to send a text message to a Telegram channel or group using PowerShell through a bot API. This can be useful for instant notifications about various events in your infrastructure, script or scheduled task execution results.

First, you need to create a new bot in Telegram using @BotFather. Find this bot in the Telegram client and send it the following commands:

  • /start
  • /newbot

Specify the name of the bot and your username. BotFather will generate an HTTP token for you, which you need to copy and save.

To send a message to a Telegram chat or a specific user, you need to obtain their ID. In this case, I will be sending a message to myself, so I will use @my_id_bot to get my ID.

  • /start

Your user ID: 987654321

The token of the bot and the name of your user (group) must be specified to send a message to Telegram:

$tg_token="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$tg_chat_id="987654321"
To connect to the Telegram API, it is mandatory to use TLS 1.2 protocol. Make sure that TLS 1.2 is enabled on your Windows operating system. By default, PowerShell may use outdated SSL 3.0, TLS 1.0 or TLS 1.1 protocols for connection. To use TLS 1.2 in the current session, execute the command:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 
The command to send a message in Telegram is:

$message="Тестовое сообщение в Telegram из PowerShell"
$Response = Invoke-RestMethod -Uri "https://api.telegram.org/bot$($Telegramtoken)/sendMessage?chat_id=$($Telegramchatid)&text=$($Message)"

You should receive a message from the bot.

To make messages more visual and colorful, you can use emoji characters and HTML formatting:

$message= $currend_data + "⚠️ Update script <b>Update1C</b> completed with errors"
$Response = Invoke-RestMethod -Uri "https://api.telegram.org/bot$($tg_token)/sendMessage?chat_id=$($tg_chat_id)&text=$($Message)&parse_mode=html"


If your network access to the Internet is through a proxy server, you can specify it using the -Proxy parameter of the Invoke-WebRequest cmdlet. You can use the -ProxyCredential argument to authenticate to the proxy.

$Response = Invoke-RestMethod -Uri "https://api.telegram.org/bot$($Telegramtoken)/sendMessage?chat_id=$($Telegramchatid)&text=$($Message)" –Proxy "http://192.168.31.55:3128"

In PowerShell 7.x, the Invoke-WebRequest cmdlet uses the proxy settings specified in environment variables. More information about using proxies in PowerShell can be found in the documentation.

The script for sending messages to Telegram can be organized as a function and added to the PowerShell profile file in Windows:

    function Send-Telegram {
        [CmdletBinding()]
        param(
            [Parameter()]
            [string] $Message
        )    
        $tg_token="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        $tg_chat_id="987654321"
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        $Response = Invoke-RestMethod -Uri "https://api.telegram.org/bot$($tg_token)/sendMessage?chat_id=$($tg_chat_id)&text=$($Message)&parse_mode=html"
        return $Response    
    }

To open the PowerShell profile file, which is automatically applied when launching the powershell.exe/pwsh.exe process, run the following command:

notepad $PSHOME\Profile.ps1


You can now use the function for sending a message to a Telegram channel from any PowerShell script. To do this, simply execute the following command:

Send-Telegram  "My test message"
If you use Teams as your primary messenger, you can also send messages to a Teams channel using PowerShell.

Important aspects.

1. To send messages to a channel using PowerShell, you need to:
  1. Add the bot as an admin to the chat/channel.
  2. Start the @RawDataBot and forward any message from the chat or channel to it.
  3. It will return the JSON code of the message, and you need to copy the chat ID from it.

2. If you need to enable the execution of scripts in Windows, for example, from Task Scheduler, the *.ps1 script will not be executed. To do this, you need to configure the PowerShell Execution Policy to allow script execution.

You can do this by using the parameter -ExecutionPolicy Bypass when running a PowerShell script: 

%windir%\System32\WindowsPowerShell\v1.0\powershell.exe -Noninteractive -ExecutionPolicy Bypass –Noprofile -file c:\path\PSScript.ps1
3. How can I add the execution of a PowerShell script to an MSSQL backup plan?

  1. Create a new SQL job in Management Studio with a "PowerShell job step," specifying the path to the script or running the function directly from there.
  2. Add the "Execute SQL Server Agent Job Task" to the last task of the backup plan and select your job.

The scripts are executed by SQL Server Agent.

Отправить комментарий

Добавлять новые комментарии запрещено.*

Новые Старые