You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell打印机自动映射脚本过滤逻辑故障求助

问题原因与解决方案

核心问题

你的脚本过滤逻辑失效的原因有两个:

  1. 打印机存在性判断错误:$ACTIVE_PRINTERS = Get-Printer返回的是打印机对象集合,不是字符串数组。直接调用$ACTIVE_PRINTERS.Contains($PrinterName)时,PowerShell会尝试在集合中寻找和字符串$PrinterName完全相等的对象,而非匹配对象的Name属性,因此这个判断永远返回$false,导致每次都会执行添加操作。
  2. 未检查端口是否已存在:即使删除了打印机,对应的IP端口可能仍然保留在系统中,直接执行Add-PrinterPort会触发重复创建错误。

修正后的脚本

# 获取当前已安装的打印机名称列表(仅提取名称,方便判断)
$ACTIVE_PRINTER_NAMES = (Get-Printer).Name
# 获取当前已存在的打印机端口名称列表
$EXISTING_PORTS = (Get-PrinterPort).Name

try {
    if (Get-Variable -Name LM -ErrorAction SilentlyContinue) {
        Write-Host "Lexmark Printers"
        foreach ($PrinterName in $LM.Keys) {
            $ip = $LM[$PrinterName]
            
            # 先判断打印机是否已存在
            if ($ACTIVE_PRINTER_NAMES -notcontains $PrinterName) {
                # 判断端口是否已存在,不存在再创建
                if ($EXISTING_PORTS -notcontains $ip) {
                    Add-PrinterPort -Name $ip
                    Write-Host "已创建端口: $ip"
                }
                # 添加打印机
                Add-Printer -DriverName "Lexmark Universal v2" -Name $PrinterName -PortName $ip
                Write-Host "已映射打印机: $PrinterName -> $ip"
            } else {
                Write-Host "$PrinterName : $ip 已存在,跳过映射"
            }
        }
    } else {
        Write-Host "No Lexmark Printers Located in $sqdrn"
    }
} catch {
    Write-Error "发生错误: $($_.Exception.Message)"
}

关键修改说明

  • 提取名称属性:通过(Get-Printer).Name直接获取所有已安装打印机的名称字符串数组,用-contains运算符判断目标打印机是否存在,这是PowerShell中判断集合元素的正确方式。
  • 端口存在性检查:提前获取所有已存在的端口名称,添加端口前先判断是否存在,避免重复创建报错。
  • 细化日志输出:区分“已创建端口”“已映射打印机”“已存在跳过”三种情况,方便排查执行状态。

额外提示

如果删除打印机后端口仍然残留,可以手动清理或在脚本中添加端口清理逻辑(仅在确认不需要该端口时使用):

# 示例:删除未被任何打印机使用的IP端口
Get-PrinterPort | Where-Object { $_.Name -match '^\d+\.\d+\.\d+\.\d+$' -and -not (Get-Printer | Where-Object { $_.PortName -eq $_.Name }) } | Remove-PrinterPort

内容的提问来源于stack exchange,提问作者FamEliteGamer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 01:16:01