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

PowerShell筛选排除列表外打印机失败,求助语法修正或替代方案

PowerShell打印机过滤问题修正方案

问题根源

你当前代码使用-notmatch结合管道符|拼接排除列表,若排除文件中存在含正则特殊字符(如.、*、+)的打印机名称,会导致正则匹配逻辑失效,无法正确过滤目标设备;此外文件中的空行也会引入无效匹配规则,干扰结果。

修正方法1:修复正则匹配逻辑

对排除列表的每个条目转义正则特殊字符,同时过滤空行,确保匹配精准:

$PrinterServers = Get-ADComputer -Filter * | Where-Object Name -Like 'SC-PS-0*'

# 读取排除列表,过滤空行并转义正则特殊字符
$ExcludeList = Get-Content .\myExcludedPrinters.txt | Where-Object { $_ -notmatch '^\s*$' } | ForEach-Object { [regex]::Escape($_) }
$ExcludePattern = $ExcludeList -Join '|'

$PrinterReport = ForEach($ps in $PrinterServers){
    Get-Printer -ComputerName $ps.Name | 
        Where-Object { 
            $_.Name -notlike '*Redirected*' -and 
            ($ExcludePattern -eq '' -or $_.Name -notmatch $ExcludePattern)
        } | 
        Select-Object ComputerName, Name, PortName, Location, Comment, Shared
}

关键调整

  • [regex]::Escape($_):转义每个排除条目中的正则特殊字符,避免匹配异常
  • 过滤空行:移除文件中无效的空白条目,防止引入错误匹配规则
  • 空列表判断:当排除列表为空时,跳过正则匹配逻辑,避免返回空结果

修正方法2:使用精确匹配替代正则

若只需精确匹配打印机名称,这种方法更简单可靠:

$PrinterServers = Get-ADComputer -Filter * | Where-Object Name -Like 'SC-PS-0*'

# 读取排除列表并过滤空行
$ExcludeList = Get-Content .\myExcludedPrinters.txt | Where-Object { $_ -notmatch '^\s*$' }

$PrinterReport = ForEach($ps in $PrinterServers){
    Get-Printer -ComputerName $ps.Name | 
        Where-Object { 
            $_.Name -notlike '*Redirected*' -and 
            $_.Name -notin $ExcludeList
        } | 
        Select-Object ComputerName, Name, PortName, Location, Comment, Shared
}

优势

  • 无需处理正则特殊字符,完全按照名称精确匹配
  • 代码逻辑直观,降低出错概率

后续扩展:更新排除列表与告警

获取到新打印机后,可自动更新排除列表并触发告警(示例):

if ($PrinterReport) {
    # 将新打印机名称追加到排除文件
    $PrinterReport.Name | Out-File .\myExcludedPrinters.txt -Append -Encoding utf8
    # 触发告警(可替换为邮件、Teams通知等方式)
    foreach ($printer in $PrinterReport) {
        Write-Warning "发现新打印机:$($printer.ComputerName) - $($printer.Name)"
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 22:01:03