Windows server send message

В Windows Server 2012 в консоли Server Manager в разделе управления настройками ролей Remote Desktop Services при выборе определённой Коллекции нам доступно окно управления клиентскими подключениями к серверам нашей фермы RDS, однако по какой-то странной причине разработчики этой самой консоли посчитали что функцию выбора более одного пользователя для отправки сообщения реализовывать не нужно, …наверно чтобы администраторам жизнь мёдом не казалась..

image

Поэтому в момент возникновения такой необходимости пришлось на скорую руку слепить небольшой PowerShell скрипт (должен выполняться на любом из серверов фермы), который позволит выполнить массовую рассылку сообщения всем подключенным пользователям фермы.

# $ConnectionBroker - Активный сервер RDCB. Если не указан, будет произведена попытка выявить его автоматически (для этого обязательно чтобы скрипт выполнялся на одном из серверов фермы RDS)
# $SessionHostCollection – Имя RD-коллекции в которой нужно вывести сообщение.
# 
$ConnectionBroker = ""
$SessionHostCollection = "KOM-AD01-RDCOLL"

$MessageTitle = "Сообщение от тех.поддержки SAP"
$MessageText = "Уважаемые коллеги! 
В связи с проведением работ по расчету зарплаты - 
просьба в программе SAP Персонал с 11:00 до конца дня 
с табельными номерами не работать!"

If ($ConnectionBroker -eq "") {
 $HAFarm = Get-RDConnectionBrokerHighAvailability
 $ConnectionBroker = $HAFarm.ActiveManagementServer
}

$Sessions = Get-RDUserSession -ConnectionBroker $ConnectionBroker -CollectionName $SessionHostCollection
ForEach ($Session in $Sessions) {
Send-RDUserMessage -HostServer $Session.ServerName -UnifiedSessionID $Session.UnifiedSessionID -MessageTitle $MessageTitle -MessageBody $MessageText 
}

В результате все активные пользователи на всех серверах фермы RDS получат всплывающее сообщение которое трудно не заметить… 

image

 Частенько возникает необходимость предупредить пользователей терминального сервера о перезагрузке или технических работах. Проще всего это сделать сообщением, которое отображается по центру экрана в RDP-сессии. В Windows Server 2003/2008 R2 сообщение можно было отправить прямо из диспетчера задач, что на мой взгляд было весьма удобно. В следующих версиях Windows Server эту возможность убрали, но оставили консольную утилиту msg, которая вполне справляется с этой задачей.

1. С помощью диспетчера задач. Подходит для Windows Server 2003/2008 R2.

Диспетчер задач —> Вкладка Пользователи —> ПКМ —> Отправить сообщение.

 

2. Консольной утилитой msg. Подходит для любой версии Windows Server.

Утилита msg имеет достаточно большой функционал, но лично я обычно пользуюсь всего тремя командами.   

Сообщение всем пользователям текущего сервера:

msg * «Сообщение»

Сообщение конкретному пользователю:

msg ИмяПользователя «Сообщение»

Сообщение пользователю другого сервера в локальной сети:

msg /server:ИмяСервера ИмяПользователя «Сообщение»

По умолчанию сообщение висит 1 минуту. Изменить время ожидания можно ключом /time:времявсекундах. Пример:

msg * /time:3200 «Сообщение»

Hi. It’s me. You are trying to upgrade a server but there are people logged in. You want to tell them all that you’ll be doing work, so you need to send a message…

It’s easy, but you’ll write it down anyways.


Open CMD..

Type msg * "your message here"

For example:

This will output a message like this:

Cheers to being courteous.

The estimated reading time 3 minutes

RDSMessenger.ps1

UPDATE 11/09/2019: If you like this script as module or EXE see my new post

In RDServer (Remote Desktop) environmets (also know with the legacy name terminalservices) you need to notify all active users, because there is a maintenace or anything else. I searched a while to find a thin solution for that, but did not find any proper solution. So I decided to write a short powershell script to do this task.
With Windows Server 2012 a new cmdlet was introduced
https://docs.microsoft.com/en-us/powershell/module/remotedesktop/send-rdusermessage?view=win10-ps
Send-RDUserMessage

The goal:

Link to my github repository:
https://github.com/blog-it-koehler-com/rdsmessenger

You can use this cmdlet after importing on the server where you want so send the notification. This message is also displayed in remoteapps so it can be used in mixed environments with desktop and remoteapps. (WIN2012/R2, WIN2016 and WIN2019 include this module by default).

NOTE: how to find the RD-Broker? If you don’t know which server is the broker, please open your ServerManager and connect all server which are part of the collection (ServerManager tells you which one is missing)
After importing all server in ServerManager you can see the configuration and also the broker

As mentioned there is one cmdlet which generates the message for one user. The heart of my script are these few lines:

Import-Module RemoteDesktop
$broker = "FQDN of the Broker"
$userids = Get-RDUserSession -ConnectionBroker "$broker" | sort Username
foreach($uid in $userids){
            $id = (($uid).UnifiedSessionID)
             Send-RDUserMessage -HostServer $($uid.HostServer) -UnifiedSessionID $id -MessageTitle "messagetitel" -MessageBody "text in your messagebox"
             }

With the following script you see some output when you execute the script.

Import-Module RemoteDesktop
#fill message
$msgtitel = Read-Host "Type message titel"
$msg = Read-Host "Type message..."
$broker = Read-Host "Type FQDN of rd broker server"
#getting all user ids 
$userids = Get-RDUserSession -ConnectionBroker "$broker" | Sort-Object Username
$sessions = ($userids | Select-Object UserName,UnifiedSessionId)|Out-String
Write-host "Getting all active sessions on rd broker $broker" -ForegroundColor Yellow
Write-host "$sessions" -ForegroundColor Yellow
#send message to all user ids
foreach($uid in $userids){
            $id = (($uid).UnifiedSessionID)
            $user = (($uid).UserName)
            Send-RDUserMessage -HostServer $($uid.HostServer) -UnifiedSessionID $id -MessageTitle "$msgtitel" -MessageBody "$msg"
            Write-Host "Sending message to user: $user with titel: $msgtitel" -ForegroundColor Green
}
pause

here my script in action.

After this short introduction, see some tips to handle my ps script from github with parameters:

EXAMPLE 1 simple execution:

EXAMPLE 2 execution with parameters
.\rdmessenger.ps1 -rdbroker rds02.demo01.it-koehler.com -messagetitel “admin message” -message “message to display” -Verbose

EXAMPLE 3 execution with parameter -rdsessionhost
.\rdmessenger.ps1 -rdbroker rds02.demo01.it-koehler.com -messagetitel “admin message” -message “message to display” -rdsessionhost rds02.demo01.it-koehler.com

Features of this script:

  • checks modules required
  • imports modules required
  • waiting 10 seconds before notification is send to all users
  • see what it does with verbose command

Also have a look at my comments inside script if you want to know what it does.

If you have any further questions please leave me a message. If you like the tool click on helpful. Have fun sending messages to your users.

Was this article helpful?

YesNo

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как улучшить качество букв в windows 10
  • Windows boot external hard drive
  • Windows xp christmas theme
  • Tcm 2005 как запустить на windows 10
  • Twin usb joystick драйвер windows 10