B
B
Bannana_fish2022-04-14 17:08:31
PowerShell
Bannana_fish, 2022-04-14 17:08:31

How to set up sending command output to Telegram?

Hello! I am new to PowerShell and I have the following code which is supposed to send a list of blocked users to telegram.

$token = "*******"
$chat_id = "********"
$text = Search-ADAccount -LockedOut | Select Name,SamAccountName
$URI = "https://api.telegram.org/bot" + $token + "/sendMessage?chat_id=" + $chat_id + "&text=" + $file
$Request = Invoke-WebRequest -URI ($URI)

I am sure that there are blocked users, but when I run the code, I get the following error:
spoiler
Invoke-WebRequest : {"ok":false,"error_code":400,"description":"Bad Request: message text is empty"}
At line:16 char:12
+ $Request = Invoke-WebRequest -URI ($URI)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Пробовал записать заблокированных пользователей в csv файл и отправить его, но файл даже не заполняется. Использовал: Search-ADAccount -LockedOut | Select Name,SamAccountName | Export-Csv C:\temp\1.csv Get-content -Path C:\temp\1.csv

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
akelsey, 2022-04-14
@akelsey

He also writes that message text is empty, add the message to the variable (without spaces, so as not to create a new question):
$file="MyMessage"

"&text=" + $file

or change $file to $text, though it still won't send, it's better as I wrote above, for verification.

B
Bananya, 2022-04-14
@Bananya

if you send plain text, then there will be no problems

M
Maxim Kravchuk, 2022-04-14
@MaxKra1985

Telegram has another method for sending files.
If you need to send the contents of the file - then you first need to read it.

R
Roman Bezrukov, 2022-04-15
@NortheR73

1. The Telegram API expects text from you, and you offer it an array of objects - that's why the error. You need to pass $text.Name and $text.SamAccountName, and do it in loop
2. You need to add the -UsersOnly parameter to Search-ADAccount - it will work faster, because will not check other types of AD objects (computers and service accounts)
3. There is a good example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question