Created
December 8, 2020 01:18
-
-
Save mikekosulin/f80cbed768e7fb51ed40d906b720d066 to your computer and use it in GitHub Desktop.
Send message to telegram on new Windows Server RDP connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# .\telegramNotify.ps1 -WindowStyle Hidden -botToken "{YOUR_BOTTOKEN}" -chatId "{YOUR_CHAT_ID}" | |
param ($botToken, $chatId) | |
Add-Type -AssemblyName System.Web | |
[string]$dateFormat = "yyyy/MM/dd HH:mm" | |
[string]$endPoint = "https://api.telegram.org/bot$botToken/sendMessage" | |
# Unicode chars | |
[char]$nl = [char]::ConvertFromUtf32(0x000A) | |
[String]$computerEmoji = [char]::ConvertFromUtf32(0x1F5A5) | |
[String]$userEmoji = [char]::ConvertFromUtf32(0x1F464) | |
[String]$calEmoji = [char]::ConvertFromUtf32(0x1F4C5) | |
[string]$logname = 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational' | |
[int32]$logid = 21 | |
# Get the last item and convert to xml | |
$eventVal = Get-WinEvent -FilterHashtable @{Logname=$logname;ID=$logid} -MaxEvents 1 | |
[xml]$evt = $eventVal[0].ToXml() | |
# Event details | |
[string]$dateTime = [datetime]::Parse($evt.Event.System.TimeCreated.GetAttribute('SystemTime')).ToString($dateFormat) | |
[string]$userName = $evt.Event.UserData.EventXML.User | |
[string]$userIp = $evt.Event.UserData.EventXML.Address | |
# Message lines | |
[string]$firstString = "New RDP connection" | |
[string]$dateString = $calEmoji +' `' + $dateTime + '`' | |
[string]$userString = $userEmoji +' `' + $userName + '`' | |
[string]$ipString = $computerEmoji +' `' + $userIp + '`' | |
# Final string | |
[string]$messageString = $firstString + $nl + $dateString + $nl + $userString + $nl + $ipString | |
$messageString = [System.Web.HTTPUtility]::UrlEncode($messageString) | |
# Building request url | |
$requestUrl = $endPoint +"?chat_id=$chatId" +"&parse_mode=Markdown" + "&text=" + $messageString | |
Invoke-WebRequest -Method GET -Uri $requestUrl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment