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

如何使用PowerShell脚本在拷贝目录时排除含指定字符串的文件夹

解决方案

问题根因

-notin 运算符为精确匹配逻辑,无法识别通配符 *,因此你写的*SQLMonitor*规则不会触发匹配,导致排除逻辑失效。

实现代码(最小改动版本)

直接替换Where-Object的判断逻辑,使用支持通配符的-like运算符逐一匹配排除规则,即可实现需求:

$dirName = "C:\Users\xyz\Desktop\powershellScripts\destmonitors"
$excludes = "PortMonitor","ProcessMonitor","FileWatcher","UrlMonitor","*SQLMonitor*","LogMonitor"
Get-ChildItem "C:\Users\xyz\Desktop\powershellScripts\monitors\*" -Directory | Where-Object{
    $currentName = $_.Name
    # 只要匹配任意一条排除规则就过滤当前目录
    -not ($excludes | Where-Object {$currentName -like $_})
} | Copy-Item -Destination $dirName -Recurse -Force

高性能版本(适合排除项较多的场景)

如果你的排除规则数量较多,可以将通配符规则转换为正则表达式匹配,减少遍历开销,效率更高:

$dirName = "C:\Users\xyz\Desktop\powershellScripts\destmonitors"
$excludes = "PortMonitor","ProcessMonitor","FileWatcher","UrlMonitor","*SQLMonitor*","LogMonitor"
# 通配符转正则:将*替换为正则通配符.*,多条规则用或逻辑拼接
$excludeRule = $excludes.ForEach({[regex]::Escape($_).Replace('\*','.*')}) -join '|'
Get-ChildItem "C:\Users\xyz\Desktop\powershellScripts\monitors\*" -Directory | Where-Object{
    $_.Name -notmatch $excludeRule
} | Copy-Item -Destination $dirName -Recurse -Force

两种方案都可完全匹配你示例中的SQLMonitor、CSTK123_SQLMonitor、TEST_SQLMonitor、SQLMonitor_abc等文件夹,实现批量排除效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:06:05