代码之家  ›  专栏  ›  技术社区  ›  FamEliteGamer

Powershell中的自动映射脚本:过滤错误

  •  0
  • FamEliteGamer  · 技术社区  · 1 年前
    $ACTIVE_PRINTERS = Get-Printer  
    try {
        if (Get-Variable -Name LM -ErrorAction SilentlyContinue){
            Write-Host "Lexmark Printers"
            foreach ($PrinterName in $LM.Keys) {
                $ip = $LM[$PrinterName]
                if (!$ACTIVE_PRINTERS.Contains($PrinterName)) {
                    Add-PrinterPort "$ip"
                    Add-Printer -DriverName "Lexmark Universal v2" -Name $PrinterName -PortName "$ip"
                    }
                Write-Host "$PrinterName : $ip Are Mapped"
            }
          
            
        } else {
            Write-Host "No Lexmark Printers Located in $sqdrn"
            }
    } catch {
        Write-Error "An error occurred: $($_.Exception.Message)"
    }
    

    我正在尝试制作一个脚本,该脚本通过IP地址列表运行,并映射打印机和名称,映射和命名方面有效,但过滤不起作用,它只是告诉打印机:IP对存在并出错。即使通过设置和控制面板移除/取消映射打印机。以下是位于LM数组中的键值对示例。

    $LM = @{"ROOM#1"="192.168.x.1";"ROOM#2"="192.168.x.2"}

    下面是收到的错误。

    Add-PrinterPort : The specified port already exists.
    At C:\Users\foobar\Desktop\MappingPrinter.ps1:85 char:17
    +                 Add-PrinterPort "$ip"
    +                 ~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ResourceExists: (MSFT_PrinterPortTasks:ROOT/StandardCimv2/MSFT_PrinterPortTasks) [Add-PrinterPort], CimException
        + FullyQualifiedErrorId : HRESULT 0x800700b7,Add-PrinterPort
     
    Add-Printer : The specified printer already exists.
    At C:\Users\foobar\Desktop\MappingPrinter.ps1:86 char:17
    + ...             Add-Printer -DriverName "Lexmark Universal v2" -Name $Pri ...
    +                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (MSFT_Printer:ROOT/StandardCimv2/MSFT_Printer) [Add-Printer], CimException
        + FullyQualifiedErrorId : HRESULT 0x8007070a,Add-Printer
    

    我尝试过$ACTIV_PRINTERS的if语句的许多变体,对powershell相当陌生。如果有人需要更多信息,或者我没有提供足够的信息,请告诉我!

    1 回复  |  直到 1 年前
        1
  •  0
  •   Keith Langmead    1 年前

    我不知道你要去哪里 $ACTIVE_PRINTERS from,因为我找不到对该环境变量的任何引用,它也没有为我返回任何东西。

    然而,我认为 Get-Printer cmdlet应为您提供所需的信息,具体如下:

    foreach ($PrinterName in $LM.Keys) {
        $ip = $LM[$PrinterName]
        if (!($(Get-Printer).Name -like "*$PrinterName*")) {
            Add-PrinterPort "$ip"
            Add-Printer -DriverName "Lexmark Universal v2" -Name $PrinterName -PortName "$ip"
            }
        Write-Host "$PrinterName : $ip Are Mapped"
    }
    
    推荐文章