在尝试添加打印机之前如何检查打印机是否已经存在?

How can I check if a printer already exists before attempting to add it?

我最近开始使用非常基础的 PowerShell lines/scripts。我需要一些关于打印机脚本的帮助,我在登录时在用户的登录名下有 运行s。

目前,每次用户登录打印机脚本都会运行(即使添加了打印机,也会重新添加)。每次都需要一段时间,我觉得我可以更聪明地完成这项工作。

如果打印机不存在,我想将脚本重新配置为仅 运行。

下面是我的代码:

add-printer -connectionname "\PRINT01.mydomain.local\L1-Printer1"
add-printer -connectionname "\PRINT01.mydomain.local\L1-Printer2"
add-printer -connectionname "\PRINT01.mydomain.local\L1-Printer3"

Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" -Name "LegacyDefaultPrinterMode" -Value 1 –Force
$wsnObj = New-Object -COM WScript.Network
$wsnObj.SetDefaultPrinter("\PRINT01.mydomain.local\L1-Printer1")

出于隐私目的,真实姓名已被删除!

编辑

Get-Printer 输出如下:

Name                           ComputerName    Type         DriverName                PortName        Shared   Published  DeviceType     
----                           ------------    ----         ----------                --------        ------   ---------  ----------     
Microsoft XPS Document Writer                  Local        Microsoft XPS Document... PORTPROMPT:     False    False      Print          
L1-Printer1                                Local        HP Laserjet 700 PCL6      PORTPROMPT:     True     False      Print

接下我的评论,您可以采用以下方法:

$printersList = @('L1-Printer1','L1-Printer2','L1-Printer3')
$printersList | ForEach-Object -Begin {
        $printersMapped = Get-Printer
    } -Process {
        if ($_ -in $printersMapped.Name) {
            Write-Verbose -Message "$_ already mapped!"
            #continue
        }
        else {
            Write-Verbose -Message "Mapping printer $_"
            Add-Printer -ConnectionName ("\PRINT01.mydomain.local\" + $_)
        }
    } -End {
        # if printer is default do nothing.
        # else: set default.
    }    

我们可以创建一个应该存在的打印机数组。遍历每一个,同时调用 Get-Printer 来检查它是否存在。如果不是,则映射打印机。

-End 子句中有一些 sudo-code,如果尚未设置打印机,您可以将其设置为默认打印机。