PowerShell: управление принтерами и драйверами печати в Windows 10 / Server 2016
В предыдущей статье мы рассмотрели олдскульные vbs скрипты, которые можно было использовать для управления принтерами и печатью во всех версиях Windows, начиная с Windows XP. Сегодня же мы рассмотрим типовые команды для создания, удаления принтеров, портов и драйверов печати в Windows при помощи PowerShell. Рассмотренные методы управления принтерами можно использовать в современных ОС — Windows 10, 8.1 и Windows Server 2012 R2 / 2016 / 2019.
Модуль PowerShell: PrintManagement
Вместе с выходом Windows 8.1 и Windows Server 2012 R2 Microsoft выпустила новую версию PowerShell 4.0 (входит в состав Windows Management Framework 4.0), в котором был существенно расширен список командлетов по управлению сервером печати на базе Windows. Полный список командлетов, по управлению принтерами, драйверами и очередями печати, доступных в модуле PrintManagement на Windows 10 (PoSh v5) можно вывести командой:
В модуле PrintManagement доступны 22 командлета PowerShell для управления принтерами, драйверами, портами печати и очередями:
- Add-Printer – добавить (установить) новый принтер;
- Add-PrinterDriver — установить новый драйвер печати;
- Add-PrinterPort – создать порт печати;
- Get-PrintConfiguration – вывести настройки печати принтера;
- Get-Printer – вывести список принтеров, установленных на компьютере;
- Get-PrinterDriver – вывести список установленных драйверов печати;
- Get-PrinterPort — вывести список портов печати;
Подробную информацию о синтаксисе конкретной команды можно получить так:
Примеры использования команд:
Рассмотрим несколько примеров типовых сценариев управления принтерами в Windows 10 из PowerShell.
Установка драйвера печати в хранилище драйверов
Чтобы вывести список драйверов печати, который установлены в хранилище драйверов Windows:
Уставим в системе новый драйвер печати, например, HP Universal Printing PCL 6. Согласно документации, команда PowerShell для добавления драйвера должна быть такой:
Add-PrinterDriver -Name «HP Universal Printing PCL 6» -InfPath «C:\Distr\HP-pcl6-x64\hpcu118u.inf»
Однако при попытке установить драйвер подобным образом появляется ошибка:
Оказывается, драйвер из inf файла можно добавить только в том случае, если он уже находится в хранилище драйверов DriverStore (подробнее про хранилище можно почитать здесь). Получается, что с помощью команды Add-PrinterDriver установить драйвер, отсутствующий в хранилище драйверов системы нельзя. Для установки драйвера в DriverStore можно воспользоваться:
- vbs скриптом из предыдущей статьи;
- Утилитой pnputil.exe. Формат такой: pnputil.exe -i -a C:\Distr\HP-pcl6-x64\hpcu118u.inf (установить конкретный драйвер принтера) или pnputil.exe -i -a C:\Distr\HP-pcl6-x64\*.inf (установит все драйвера, найденные в inf файлах указанного каталога);
- Командлетом Add-WindowsDriver, позволяющим интегрировать драйвера в оффлайн образ Windows.
После добавления драйвер принтера в хранилище, необходимо добавить его в список доступных принт-сервере.
Add-PrinterDriver -Name «HP Universal Printing PCL 6»
Установка нового принтера с помощью PowerShell
Создадим ip порт для печати на сетевом принтере (тут можно указать как IP адрес сетевого принтера, так и имя удаленного принт-сервера):
Add-PrinterPort -Name «IP_192.168.10.26» -PrinterHostAddress «192.168.10.26»
Перед добавлением порта вы можете проверить, существует ли он:
$portName = «IP_192.168.10.26»
$checkPortExists = Get-Printerport -Name $portname -ErrorAction SilentlyContinue
if (-not $checkPortExists) <
Add-PrinterPort -name $portName -PrinterHostAddress «192.168.10.26»
>
С помощью следующей команды мы создадим в системе новый принтер и опубликуем его (откроем к нему общий доступ):
Add-Printer -Name hp2050_Office1_Buh -DriverName «HP Deskjet 2050 J510 series Class Driver» -PortName IP_192.168.10.26 -Shared -ShareName «hp2050_1_BUh» –Published
Rename-Printer -Name «hp2050_Office1_Buh» -NewName » hp2050_Salary»
После выполнения указанных команд в системе появится новый принтер с общим доступом под именем hp2050_Office1_Buh.
Вывод списка принтеров на сервере печати с помощью PowerShell
Выведем полный список принтеров, установленных на данном компьютере:
Как вы видите, команда показывает имя принтера, тип (локальный или сетевой), драйвер, порт печати, открыт ли к принтеру общий доступ и опубликован ли принтер в AD.
Большинство командлетов модуля PrintManagement можно использовать для просмотра состояния и управления принетрами, драйверами и очередями печати на удаленных компьютерах. Имя удаленного компьютера или сервера указывается в качестве аргумента параметра –ComputerName.
С помощью PowerShell вы можете получить информацию об установленных принтерах на удаленном компьютере (принт-сервере), для этого выполните команду:
Get-Printer -ComputerName msk-prnt1 | Format-List Name,DriverName
Чтобы вывести только список принтеров с общим доступом, используйте команду:
Get-Printer -ComputerName msk-prnt1 | where Shared -eq $true | fl Name
Подключение сетевого принтера из PowerShell
Чтобы подключить принтер с сервера печати, используйте команду:
Add-Printer -ConnectionName \\msk-prnt1\HPCL3020
Windows 10 использует последний принтер, на который выполнялась печать в качестве принтера по умолчанию, если вы хотите использовать фиксированный принтер по-умолчанию, выполните команду:
Set-ItemProperty -Path «HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows» -Name «LegacyDefaultPrinterMode» -Value 1 –Force
Чтобы установить принтер по-умолчанию используйте следующие команды:
$wsnObj = New-Object -COM WScript.Network
$wsnObj.SetDefaultPrinter(%PrinterName%)
Удаление принтера с помощью PowerShell
Чтобы удалить принтер, нужно выполнить такую команду PowerShell:
Remove-Printer -Name «hp2050_Office1_Buh»
Вы можете удалить конкретный драйвер при помощи командлета Remove-PrinterDriver:
Remove-PrinterDriver -Name «HP Universal Printing PCL 6»
Set-Printer
Updates the configuration of an existing printer.
Syntax
Description
The Set-Printer cmdlet updates the configuration of the specified printer.
Use the KeepPrintedJobs parameter to make a printer keep printed jobs.
You can specify the printer to update by using either a printer object retrieved by the Get-Printer cmdlet, or by specifying a printer name.
You can use wildcard characters with Set-Printer. You can use Set-Printer in a Windows PowerShell remoting session.
You need administrator credentials to run Set-Printer.
Examples
Example 1: Set printer to keep printed jobs
This command configures the Microsoft XPS Document Writer printer to keep printed jobs.
Example 2: Set printer to keep printed jobs by using a printer object
The first command gets the printer named Microsoft XPS Document Writer by using the Get-Printer cmdlet. The command stores the result in the $Printer variable.
The second command assigns a value of $True to the KeepPrintedJobs property of the $Printer object.
The final command sets the value of revised value of $Printer.
Parameters
-AsJob
Runs the cmdlet as a background job. Use this parameter to run commands that take a long time to complete.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-BranchOfficeOfflineLogSizeMB
Specifies the maximum size, in megabytes, of the branch office remote offline log file for this printer. You cannot specify this parameter for unshared queues or queues that do not have branch office enabled.
Type: | UInt32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-CimSession
Runs the cmdlet in a remote session or on a remote computer. Enter a computer name or a session object, such as the output of a New-CimSession or Get-CimSession cmdlet. The default is the current session on the local computer.
Type: | CimSession [ ] |
Aliases: | Session |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-Comment
Specifies the text to add to the Comment field for the specified printer.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-ComputerName
Specifies the name of the computer on which the printer is installed.
Type: | String |
Aliases: | CN |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-Confirm
Prompts you for confirmation before running the cmdlet.
Type: | SwitchParameter |
Aliases: | cf |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-Datatype
Specifies the data type the printer uses to record print jobs.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-DisableBranchOfficeLogging
Indicates whether branch office remote logging is disabled. You cannot specify this parameter for unshared queues.
Type: | Boolean |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-DriverName
Specifies the name of the printer driver for the printer.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-InputObject
Specifies the input object that is used in a pipeline command.
Type: | CimInstance [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
-KeepPrintedJobs
Specifies whether the printer jobs in the queue are kept.
Type: | Boolean |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-Location
Specifies the location of the printer.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the name of the printer to modify.
Type: | String [ ] |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
-PassThru
Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-PermissionSDDL
Specifies the permissions for the printer as an SDDL string.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-PortName
Specifies the name of the port that is used or created for the printer.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-PrintProcessor
Specifies the name of the print processor used by the printer.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-Priority
Specifies the relative queue priority.
Type: | UInt32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-Published
Specifies whether the printer is published in the network directory service.
Type: | Boolean |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-RenderingMode
Specifies the rendering mode for the printer. The acceptable values for this parameter are:
- SSR
- CSR
- BranchOffice
Type: | RenderingModeEnum |
Accepted values: | SSR, CSR, BranchOffice |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-SeparatorPageFile
Specifies the path of and name of the separator page to be used by the printer.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-Shared
Specifies whether the printer is shared.
Type: | Boolean |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-ShareName
Specifies the name by which to share the printer on the network. To change the share state of a printer, specify the Shared parameter.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-StartTime
Specifies the starting time of printer availability.
Type: | UInt32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-ThrottleLimit
Specifies the maximum number of concurrent operations that can be established to run the cmdlet. If this parameter is omitted or a value of 0 is entered, then Windows PowerShellВ® calculates an optimum throttle limit for the cmdlet based on the number of CIM cmdlets that are running on the computer. The throttle limit applies only to the current cmdlet, not to the session or to the computer.
Type: | Int32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-UntilTime
Specifies the ending time of printer availability.
Type: | UInt32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-WhatIf
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: | SwitchParameter |
Aliases: | wi |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
-WorkflowPolicy
Enables an administrator to associate a given printer with a specific Workflow application. This parameter does not allow the administrator to override the device-app association that was made using the device metadata service.