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

如何在PowerShell中批量远程删除含指定字符的打印机

远程删除指定名称的打印机解决方案

原代码存在的问题

  • foreach 语法错误,正确格式应为 foreach ($printer in $PrinterResults)
  • 使用 -contains 判断字符串包含子串是错误的,该运算符用于检查集合是否包含指定元素,字符串包含判断应使用 -like 或 -match
  • 远程执行删除命令时,脚本块内无法直接引用本地变量 $PrinterResults,需要通过 $using: 关键字传递变量

修正后的代码方案

方案一:本地筛选后远程删除

先获取所有打印机名称,本地筛选符合条件的,再逐个远程删除:

$Computer = "AaronsComputer"
$PrinterResults = Invoke-Command $Computer -ScriptBlock { Get-Printer | Select-Object -ExpandProperty Name }

foreach ($printer in $PrinterResults) {
    if ($printer -like "*HJK*" -or $printer -like "*LSG*") {
        Invoke-Command $Computer -ScriptBlock { Remove-Printer -Name $using:printer }
        Write-Host "已删除打印机:$printer"
    }
}

方案二:远程直接完成筛选与删除(更高效)

将筛选和删除逻辑放在同一个远程脚本块中,减少远程调用次数:

$Computer = "AaronsComputer"
Invoke-Command $Computer -ScriptBlock {
    Get-Printer | 
        Where-Object { $_.Name -like "*HJK*" -or $_.Name -like "*LSG*" } |
        Remove-Printer -WhatIf
}

说明:先加上 -WhatIf 参数测试执行效果,确认无误后再移除该参数执行实际删除操作。

关键说明

  • -like "*关键词*" 用于模糊匹配包含指定子串的打印机名称,* 是通配符
  • $using: 关键字用于在远程脚本块中引用本地变量,确保变量能正确传递到目标机器
  • 方案二的效率更高,因为只需要一次远程连接,而方案一需要多次远程调用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:45:39