
Для оповещения пользователей о различных событиях, вы можете выводить различные графические уведомления из скриптов PowerShell. В PowerShell можно использовать всплывающие уведомления в трее Windows или модальные окно для получения информации от пользователя или подтверждения действия.
These days, the print server is not exactly the most important network service out there, but it is still a very important function for many companies and it’s unlikely to disappear anytime soon.
Many companies still use printers to print out reports, invoices and other documents, so it’s important to know how to set up and configure this kind of service. And by using PowerShell, you can save yourself a lot of time and also automate repetitive tasks.
- Part 1 – Install the Print Server role using PowerShell
- Part 2 – Deploy a shared printer on the print server
Arrays are a fundamental data structure in any programming language, and PowerShell is no exception. An array is a collection of items accessed by their index or iterated over. PowerShell makes it easy to work with arrays, whether you’re storing a list of names, numbers, or more complex objects. I will explain how to print arrays in PowerShell in this PowerShell tutorial.
Before you print an array in PowerShell, you must declare and initialize it. Here’s how you can create an array in PowerShell:
# Declaring an array with explicit values
$myArray = @(1, 2, 'three', 'four')
# Declaring an array with a range of numbers
$numberArray = 1..10Basic Printing of Arrays
# Printing an array with Write-Output
Write-Output $myArrayYou can also see the output in the screenshot below after I executed the code using Visual Studio Code.

Accessing Individual Items
Sometimes, you may want to print a specific item from an array. You can do this by specifying the index of the item:
# Printing the first item of the array
Write-Output $myArray[0]
# Printing the third item of the array
Write-Output $myArray[2]Remember, PowerShell arrays are zero-indexed, which means the first item is at index 0.
Looping Through Arrays
To print each item in an array, you can loop through the array using a foreach loop:
# Using foreach to print each item
foreach ($item in $myArray) { Write-Output $item
}Advanced Printing with Custom Formatting in PowerShell
If you need to print your array in PowerShell with custom formatting, you can use a foreach loop in combination with string formatting:
# Printing each item with custom formatting
foreach ($item in $myArray) { Write-Output "Item: $item"
}Joining Array Elements
Another way to print an array is to join the elements into a single string in PowerShell. You can use the -join operator for this purpose:
# Joining array elements with a comma
$joinedArray = $myArray -join ', '
Write-Output $joinedArrayExporting Arrays to a File
If you want to print your array to a file in PowerShell, you can use the Out-File cmdlet:
# Exporting array to a text file
$myArray | Out-File -FilePath C:\path\to\your\file.txtConclusion
Printing arrays in PowerShell is straightforward. Whether you’re printing the entire array, specific elements, or iterating through each item, PowerShell provides the flexibility to display the data.
In this PowerShell tutorial, I have explained different ways to print an array in PowerShell.
You may also like:
While I can’t fully test borderless printing since I don’t have a printer to test it with, I was able to test enable duplex printing using the same method.
We first create a PrintServer object. You can either use LocalPrintServer for locally connected device or you can specify a print server name:
$PrintServer = New-Object System.Printing.LocalPrintServer
#$PrintServer = New-Object System.Printing.PrintServer("\\somePrintserver")$desiredAccess = New-Object System.Printing.PrintSystemDesiredAccess
# AdministratePrinter value
$desiredAccess.value__ = 983052
$printerName = "TEST"
# Create PrintQueue object using the PrintServer, printer name, and the desired access as parameters
$PrintQueue = New-Object System.Printing.PrintQueue($PrintServer,$printerName,$desiredAccess)# get UserPrintTicket from the PrintQueue
$PrintTicket = $PrintQueue.UserPrintTicketI did add some checks to make sure that the printer has the capability before changing that setting. Using $PrintQueue.GetPrintCapabilities() we can see the capabilities and verify before changing them. Due to limitation of my printer I was only able to verify this was working for changing the Duplexing property but since it’s the same as editing the PageBorderless property I believe it should still work. I left the example for Duplexing in here. You will need to add back in the code to handle actual printing since this just modifies the setting.
$exitOnNotEnabled = $true
Add-Type -AssemblyName System.Printing
# Specify desired access to modify settings
$desiredAccess = New-Object System.Printing.PrintSystemDesiredAccess
# AdministratePrinter value
# https://learn.microsoft.com/en-us/dotnet/api/system.printing.printsystemdesiredaccess?view=windowsdesktop-7.0
$desiredAccess.value__ = 983052
# change to your printer name
$printerName = "TEST"
# Create PrintServer object. Can specify a print server but here I just have printer connected locally.
$PrintServer = New-Object System.Printing.LocalPrintServer
#$PrintServer = New-Object System.Printing.PrintServer("\\somePrintserver")
# Create PrintQueue object using the PrintServer, printer name, and the desired access as parameters
$PrintQueue = New-Object System.Printing.PrintQueue($PrintServer,$printerName,$desiredAccess)
# get UserPrintTicket from the PrintQueue
$PrintTicket = $PrintQueue.UserPrintTicket
# get printer capabilities. Going to use to make sure we only change setting that the printer has
$PrintCapabilities = $PrintQueue.GetPrintCapabilities()
# check if the PageBorderlessCapability exists
if ($PrintCapabilities.PageBorderlessCapability -ne $null){ Write-Output "-------------------------" Write-Output "PageBorderless is currently set to $($PrintTicket.PageBorderless)" Write-Output "-------------------------" # check if the PageBorderlessCapability contains 'Borderless' if ($PrintCapabilities.PageBorderlessCapability.Contains("Borderless")){ Write-Output "Borderless printing capability found" Write-Output "Enable Borderless printing" # set to borderless printing $PrintTicket.PageBorderless = 1 $PrintQueue.Commit() $PrintQueue.Refresh() Write-Output "-------------------------" Write-Output "PageBorderless is currently set to $($PrintTicket.PageBorderless)" Write-Output "-------------------------" } else{ Write-Output "Borderless printing capability NOT found" }
}
else{ Write-Output "PageBorderlessCapability is null. Printer may not support it."
}
# example for duplexing since I couldn't test borderless printing
# https://learn.microsoft.com/en-us/dotnet/api/system.printing.duplexing?view=windowsdesktop-7.0
if ($PrintCapabilities.DuplexingCapability -ne $null){ Write-Output "-------------------------" Write-Output "Duplex is currently set to $($PrintTicket.Duplexing)" Write-Output "-------------------------" if ($PrintCapabilities.DuplexingCapability.Contains("TwoSidedLongEdge")){ Write-Output "Duplexing capability TwoSidedLonEdge found." Write-Output "Enabling duplex TwoSidedLonEdge" # change duplexing to "TwoSidedLonEdge" $PrintTicket.Duplexing = 3 $PrintQueue.Commit() $PrintQueue.Refresh() Write-Output "-------------------------" Write-Output "Duplex is currently set to $($PrintTicket.Duplexing)" Write-Output "-------------------------" } else{ Write-Output "Duplexing capability TwoSidedLonEdge NOT found." }
}
if (($PrintQueue.UserPrintTicket.PageBorderless -ne 1) -and $exitOnNotEnabled){ Write-Output "Borderless Printing was not enabled..exiting" exit
}
if (($PrintQueue.UserPrintTicket.Duplexing -ne 3) -and $exitOnNotEnabled){ Write-Output "Duplexing printing TwoSidedLonEdge was not enabled..exiting" exit
}
### do stuff you were doing to print ###
### change back setting if you wanted
# something like
# $PrintTicket.PageBorderless = 0
# $PrintQueue.Commit()Example Output
PageBorderlessCapability is null. Printer may not support it.
-------------------------
Duplex is currently set to OneSided
-------------------------
Duplexing capability TwoSidedLonEdge found.
Enabling duplex TwoSidedLonEdge
-------------------------
Duplex is currently set to TwoSidedLongEdge
-------------------------
Borderless Printing was not enabled..exitingNote
Code will exit if the settings for PageBorderless or Duplexing were not able to be change. $exitOnNotEnabled = $true you can change that to $false so that doesn’t happen. You could also just remove the duplexing parts since that example doesn’t pertain to the setting you actually want to change.
“Classes within the System.Printing namespace are not supported for use within a Windows service or ASP.NET application or service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions”ref
Итак начнем. Задача, которую пытались решить — это установка принтеров на терминальные серверы (нынче серверы узла сеансов) фермы. Было несколько путей:
установка с помощью групповых политик
Установка вручную — конечно, самый простой путь, но если серверов несколько, то вероятность ошибки велика, да и установка вручную — это скучно. Нужна была автоматизация, поэтому сначала выбрал групповые политики — разворачивание принтера на компьютер (на rdsh).
Выбрал установку на компьютер, потому что AD, которое мне досталось по сути не имело структуры — все пользователи размещались в одном OU. Чтобы навести порядок в AD и распределить пользователей на OU, которые соответствуют либо структуре здания либо штатному расписанию потребуется много времени.
В результате использования GPO выявил следующие нюансы:
драйверы принтеров не устанавливаются автоматически или это происходит долго;
даже если установить драйверы принтера на rdsh, то установка принтера через gpo происходит только после перезагрузки сервера;
после входа пользователя на сервер — список принтеров пуст примерно минут пять бывает больше;
принтеры очень часто не отображаются в панели управления, но отображаются в диалоговом окне печати, например в блокноте. В оснастке управления печатью развернутые принтеры не отображаются;

При удалении принтера из групповой политики принтер частенько не удаляется сразу, даже после gpupdate force.
Самое критичное — это установка принтера только после перезагрузки — довольно неприятная ситуация, когда необходимо выкинуть с терминала 50 пользователей. Поэтому начал смотреть в сторону скрипта на Powershell.
Организацию работы по установке принтера предполагал такой: принтер устанавливается вручную на сервер печати, затем запускается скрипт, который устанавливает этот принтер на все терминальные серверы фермы, с такими же настройками что и на сервере печати.

В результате сбора информации нашел хорошую статью про PrintBRM – Отказоустойчивый сервер печати на базе Windows, благодарю автора – информация была полезна. Испытал, метод рабочий, но хотелось больше контроля над алгоритмом установки, поэтому использовал Powershell.

$driversFile= "\\storage\printDrivers\drivers.txt"
$printersFile= "\\storage\printDrivers\printers.txt"
$ACLfolder = "\\storage\printDrivers\acl\"
$csvfile= "\\storage\printDrivers\printers.csv"
$folderDrivers= "\\storage\printDrivers\drivers\"
$terminals = @("tspd-01", "tspd-02", "its-01", "its-02")
$exportFlag=0
#удаляем файл списка названий драйверов
if(Test-Path $ACLfolder){Remove-Item -Path $ACLfolder -Recurse}
if(Test-Path $driversFile){Remove-Item -Path $driversFile}
if(Test-Path $printersFile){Remove-Item -Path $printersFile}
if(Test-Path $csvfile){Remove-Item -Path $csvfile}
Start-Sleep -Seconds 5
#формируем список названий драйверов
$drivers=Get-PrinterDriver | select Name | where {$_.Name -notlike "*Microsoft*" -and $_.Name -notlike "Remote*"}
foreach ($driver in $drivers) {
write $driver.Name | out-file $driversFile -Append
}
#формируем список принтеров
$printers = get-printer | where {$_.Name -notlike "*Microsoft*" -and $_.Name -notlike "Remote*"}
#создаем директорию для ACL
Mkdir $ACLfolder
foreach($printer in $printers){
Write $printer.Name | out-file $printersFile -Append
#экспортируем ACL принтера в текстовый файл
$aclfile=$ACLfolder+$printer.Name+".txt"
(Get-Printer $printer.Name -Full).PermissionSDDL | Out-File $aclfile
}
#формируем csv файл с информацией о принтере
get-printer | where {$_.Name -notlike "*Microsoft*" -and $_.Name -notlike "Remote*"} |Export-CSV $csvfile -NoTypeInformation -Encoding UTF8
#функция экспорта драйверов
function ExportDrivers($folderDrivers){ #очищаем папку с драйверами if(Test-Path $folderDrivers){Remove-Item -Path $folderDrivers -Recurse} #получаем список драйверов принтеров $PrintDriver = Get-WindowsDriver -Online | where {($_.ClassName -like "Printer")} foreach ($print in $PrintDriver){ write $print #Записываем название драйверов НЕ от микрософта if($print.ProviderName -ne "Microsoft"){ #Создаем имя папки $folderName=($folderDrivers + $print.Driver).replace('.inf','') write $folderName #Создаем папку Mkdir $folderName #экспортируем драйвера принтеров в папку pnputil.exe /export-driver $print.Driver $folderName } }
}
#Запуск экспорта
if($exportFlag -eq 1){ExportDrivers -folderDrivers $folderDrivers}
Write "_____________________"
$pass = "Morkovka10"
$us="Domain\mylogin"
$password = ConvertTo-SecureString -String $pass -AsPlainText -Force
$cred= New-Object System.Management.Automation.PSCredential ($us, $password )
#Запуск удаленной сесии
foreach($server in $terminals){
$s = New-PSSession -computerName $server -authentication CredSSP -credential $cred
Invoke-Command -Session $s -Scriptblock { #проброс перемнных в сессию $csvfile=$using:csvfile $ACLfolder= $using:ACLfolder $folderDrivers=$using:folderDrivers $driversFile=$using:driversFile $h = hostname write "____________________________________ $h ________________________________________________________________________" #устанавливаем драйвера в хранилище драйверов write "install drivers!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" $folderDrivers=$folderDrivers+"*.inf" pnputil.exe /add-driver $folderDrivers /subdirs /install write "install drivers!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" #добавляем отсутствующие драйвера write "_______________________________" Write "добавляем отсутствующие драйвера принтеров из хранилища драйверов" $drivers = Get-Content -Path $driversFile foreach ($driver in $drivers){ if((Get-PrinterDriver -Name $driver).Count -eq 0){ Add-PrinterDriver -Name $driver } } write "_______________________________" #Получаем массив объектов - список принтеров на принтсервере из csv $printers = $printers =Import-CSV -Path $csvfile #Получаем массив локальных принтеров $localPrinters = get-printer -Full | where {$_.Name -notlike "*Microsoft*" -and $_.Name -notlike "Remote*"} #удаляем локальные принтеры которых нет на принтсервере foreach ($localP in $localPrinters){ $match = $printers -match $localP.Name if($match.Count -eq 0){ $pname=$localP.Name write "REMOVE $pname - !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" Remove-Printer -Name $localP.Name } } Foreach($p in $printers){ write $p.Name write $p.DriverName write $p.PortName $aclfile=$ACLfolder+$p.Name+".txt" $perms = Get-Content -Path $aclfile if((Get-Printer -Name $p.Name).Count -ne 0){ #синхронизируем ACL Set-Printer $p.Name -PermissionSDDL $perms #Получаем локальный принтер $localprinter= Get-Printer -Name $p.Name #Проверяем порт if($localprinter.PortName -ne $p.PortName){ write "порт НЕ совпадает" #Добавляем порт если его нет if((Get-PrinterPort -Name $p.PortName).Count -eq 0){ Add-PrinterPort -Name $p.PortName -PrinterHostAddress $p.PortName } #Добавляем порт принтеру Set-Printer -Name $p.Name -PortName $p.PortName }else{write "порт совпадает"} #Проверяем драйвер if($localprinter.DriverName -ne $p.DriverName){ Set-Printer -Name $p.Name -DriverName $p.DriverName } } else { #Добавляем порт if((Get-PrinterPort -Name $p.Name).Count -eq 0){ Add-PrinterPort -Name $p.PortName -PrinterHostAddress $p.PortName } #Добавляем принтер Add-Printer -Name $p.Name -DriverName $p.DriverName -PortName $p.PortName #Добавляем ACL Set-Printer $p.Name -PermissionSDDL $perms } } }
} В результате мы получили:
удаленную установку принтеров на терминальные серверы без необходимости их перезагрузки;
единый сервер администрирования печати — сервер‑печати, который является эталонным — именно с него копируются все настройки устанавливаемых принтеров;
простой метод развертывания принтеров, поэтому его можно передать специалистам службы поддержки — установил принтер на сервер печати, настроил права и затем запустил скрипт — все просто!
Сервер печати — занимает мало места (в виде ВМ), поэтому можно быстро и легко его бекапить каждый день, поэтому не страшно, если техподдержка начудит — его быстро можно восстановить.
Только зарегистрированные пользователи могут участвовать в опросе. Войдите, пожалуйста.
Как организована установка принтеров в вашей организации?
Проголосовали 28 пользователей. Воздержались 4 пользователя.
Write-Output and Echo in PowerShell
echo ["message"]echo "This is a sentence." 
The output prints the This is a sentence message.
- Text printing.
- Object printing.
- Formatting the output using the
-Formatcmdlets. - Specifying the output encoding.
- Redirecting the output to a file.
- Parameters that allow users to customize the output.
Example of echo in PowerShell
echo "This is another sentence."
$name = "Sara"
echo $name
The output prints the content of the variable.
Available cmdlets are:
Format-Custom. Customizes the output with different views.Format-Hex. Shows data in hexadecimal format.Format-List. Creates lists of objects’ properties.Format-Wide. Depicts a single object’s property spanning across the screen.Format-Table. Presents the data in the form of a table.
echo "Number", "Name", "Age", "Location" | Format-Table
Function CheckIfNumberIsPrime($num) {
if ($num -lt 2) { echo "$num is not a prime number" } else { $isPrime = $true for ($i = 2; $i -lt $num; $i++) { if ($num % $i -eq 0) { $isPrime = $false break } } if ($isPrime) { echo "$num is a prime number" } else { echo "$num is not a prime number" } }
}To test the function, run:
CheckIfNumberIsPrime($num)Replace ($num) with a prime number, for example:
CheckIfNumberIsPrime(7)
The output confirms seven is a prime number. Next, try 135:
CheckIfNumberIsPrime(135)
The output verifies 135 is not a prime number.
Example of Write-Output in PowerShell
The Write-Output cmdlet is a powerful command which prints text, objects, and formatted output to the console.
The basic Write-Output syntax is:
Write-Output [object]Write-Output "This is another sentence."
Function PrimeNumber?($num) { if ($num -lt 2) { Write-Output "$num is not a prime number" } else { $isPrime = $true for ($i = 2; $i -lt $num; $i++) { if ($num % $i -eq 0) { $isPrime = $false break } } if ($isPrime) { Write-Output "$num is a prime number" } else { Write-Output "$num is not a prime number" } }
Test the function with the number seven by running:
PrimeNumber?(7)
Next, test with 135:
PrimeNumber?(135)
The outputs confirm seven is a prime number while 135 is not.
Вывести всплывающее сообщение на экран с помощью PowerShell
Для вывода простых модального диалогового окна в Windows можно воспользоваться Wscript классами подсистемы сценариев Windows. Следующий PowerShell код выведет обычное текстовое окно с вашим текстом и кнопкой OK.
$wshell = New-Object -ComObject Wscript.Shell
$Output = $wshell.Popup("Скрипт формирования отчета выполнен")

Вы можете настроить вид модального окна такого сообщения и добавить кнопки действия для пользователей. Например, чтобы вывести всплывающее окно с кнопками Да и Нет, выполните:

$Output = $wshell.Popup("Скрипт формирования отчета завершен! Хотите вывести его на экран?",0,"Отчет готов",4+32)
Если пользователь нажмет Да, команда вернет значение
6
, а если Нет –
7
.
В зависимости от выбора пользователя вы можете выполнить какое-то действие, или завершить скрипт.
switch ($Output) { 7 {$wshell.Popup('Нажата Нет')} 6 {$wshell.Popup('Нажата Да')}
default {$wshell.Popup('Неверный ввод')} } Общий синтаксис и параметры метода Popup:
- <Text> — текст сообщения.
- <SecondsToWait> — необязательный, число. Количество секунд, по истечении которого окно будет автоматически закрыто.
- <Title> — текст заголовка окна сообщения (необязательный параметр).
- <Type> — комбинация флагов, определяет тип кнопок и вид значка (числовое значение, не обязательный параметр). Возможные значения флагов:
- 0 — кнопка ОК.
- 1 — кнопки ОК и Отмена.
- 2 — кнопки Стоп, Повтор, Пропустить.
- 3 — кнопки Да, Нет, Отмена.
- 4 — кнопки Да и Нет.
- 5 — кнопки Повтор и Отмена.
- 16 — значок Stop.
- 32 — значок Question.
- 48 — значок Exclamation.
- 64 — значок Information.
Команда PowerShell возвращает целое значение, с помощью которого можно узнать, какая кнопка была нажата пользователем. Возможные значения:
- -1 — таймаут.
- 1 — кнопка ОК.
- 2 — кнопка Отмена.
- 3 — кнопка Стоп.
- 4 — кнопка Повтор.
- 5 — кнопка Пропустить.
- 6 — кнопка Да.
- 7 — кнопка Нет.
Если нужно показать пользователю окно ввода и запросить данные, воспользуйтесь классом Windows Forms.
Чтобы обработать введенные пользователе данные:
if ([string]::IsNullOrWhiteSpace($input)) { Write-Host "Данные не указаны"
} else { Write-Host "Вы ввели $input"
}
Если нужно вывести всплывающее окно поверх всех окон, используйте команду:
Вывести уведомление пользователю Windows из скрипта PowerShell
С помощью класса Windows Forms можно вывести более красивые всплывающие сообщения (ballons). Следующий скрипт выведет всплывающее сообщение рядом с панелью уведомлений Windows, которое автоматически исчезнет через 10 секунд:

Для создания красочных всплывающих сообщений в Windows можно использовать отдельный PowerShell модуль BurntToast.
Установите модуля из PowerShell Gallery:
Install-Module -Name BurntToast
Теперь, например, в ранее рассматриваемый скрипт автоматического отключения от Wi-FI сети при подключении к Ethernet можно добавить уведомление с картинкой:
New-BurntToastNotification -Text "Отключение от Wi-Fi сети", "Вы были отключены от Wi-Fi сети, т.к. Вше устройство было подключено к скоростному Ethernet подключению." -AppLogo C:\PS\changenetwork.png

How to Add Network Printers Using PowerShell
Before you get started…
- To be registered with an organisation on the Jotelulu platform and to have logged in.
Part 1 – Installing the Print Server Role Using PowerShell
The very first thing you need to do is install the Print Server role on your server. You can do this either through Server Manager or PowerShell, but for the purposes of this tutorial, we’re going to stick to PowerShell.
Once installed, you will see a message telling you to restart the server to complete the installation process (2). To do this, simply run the command “Restart-Computer”.

NOTE: The server may take a while to apply the changes and restart. How long it takes will depend on your server specifications.
Part 2 – Deploying A Shared Printer on the Print Server
To see a list of all the available printer drivers on your server, run the command “Get-PrinterDriver” (3).

You can also run the command “Get-Printer” (4) to see the available printers.

Next, you need to add the printer drivers to the Driver Store. To do this, you will need to download the most recent drivers from the manufacturer’s website. It’s also worth testing the drivers on a pilot environment before adding them to your production environment.
To do add the drivers to Driver Store, run the command “pnputil.exe -i -a <PATH>” (5), where <PATH> is the complete file path for the .inf file that contains the drivers.
Here’s an example:
pnputil.exe -i -a “C:\HP Universal Print Driver\ps-x64-7.0.1.24923\hpbuio2001.inf”
Once you’ve run the command, check the lines that read “Total attempted:” and “Number successfully imported:”. If everything has been done correctly, the two numbers should be the same (6).

Now that the drivers have been added to Driver Store, it’s time to install them on the print server. To do this, run the command “Add-PrinterDriver -Name <Name>” (7), where <Name> is the name of the printer being installed.
Add-PrinterDriver –Name “HP Universal Printing PCL 6”

Next, you need to Add the standard TCP/IP printer port by running “Add-PrinterPort -Name <IP Address> -PrinterHostAddress <IP Address>” (8), where <IP> is the printer’s IP address.
Add-PrinterPort -Name “10.1.1.123” -PrinterHostAddress “10.1.1.123”

- Name <Printer_Name>: is the name of the printer.
- DriverName <Driver_Name>: is the name of the printer driver.
- Shared: indicates that it’s a shared queue.
- ShareName <Share_Name>: is the name that the printer will be shared as.
- PortName <Port>: the port used for sharing.
- Published: indicates that the queue has been published.
NOTE: If you want to keep things simple, there’s no harm in entering the same name for all these parameters.


Alternatively, you could go to Printers & Scanners to check that you can see the new printer (11) and access the print queue, management settings, etc.

Отправка сообщения пользователю на удаленный компьютер
С помощью PowerShell вы можете отправить всплывающее сообщение пользователю на удаленный компьютер. Сначала нужно получить список сессии пользователей на удаленном компьютере (в случае RDS сервера):

Чтобы отправить сообщение в сессию пользователя на удаленном компьютер, выполните команду:
MSG kbuldogov /server:rds1 "Сервер будет перезагружен через 10 минут. Закройте документы"
Если всплывающее сообщение нужно отправить всем пользователям укажите * вместо имени пользователя:
MSG * /server:rds1 "Срочное сообщение всем! "

Для отправки всплывающего графического уведомления на удаленный компьютер можно воспользоваться скриптом RemoteSendToasNotification.ps1 из нашего GitHub репозитория ( https://github.com/winadm/posh/blob/master/scripts/RemoteSendToasNotification.ps1). Для подключения к удаленному компьютеру используется командлет Invoke-Command, который использует WinRM.

Summary
Thanks for choosing Jotelulu!
Write-Host vs. Echo
Write-Output, on the other hand, writes data to the PowerShell pipeline. The output is displayed on the screen if there is no subsequent command in the pipeline to receive this data.
A key Write-Host advantage is the customization capability. Write-Host supports a broader range of formatting options.
To specify the output’s foreground and background colors, use:
Write-Host "Text" -ForegroundColor [Color] -BackgroundColor [Color]For instance, print a line This sentence is white with a magenta background:
Write-Host "This sentence is white with a magenta background" -ForegroundColor White -BackgroundColor Magenta
The output is displayed in the requested format.
Next, learn how to set environment variables in Windows.




