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

PowerShell 如何验证目录内文件名是否匹配TXT文件存储的客户编码

PowerShell文件名匹配逻辑问题修复

问题根因

  • 操作符用法倒置:-contains 是集合包含判断操作符,要求左侧为待检查的数组/集合,右侧为单个元素,你的代码里把单个文件名字符串放左侧、编码集合放右侧,逻辑完全错误,所以永远返回false。
  • 匹配规则不符:-contains 执行的是完全相等匹配,仅当集合中存在和右侧元素完全一致的内容时才返回true,无法满足你「文件名包含编码子串」的需求。

修复方案

方案1:遍历编码匹配(易理解,适合编码量少的场景)

$dwhDocumentsSource = Get-ChildItem "C:\source\documents" -Filter *.edi
# Trim处理每行编码的隐形空格/换行符,避免匹配异常
$clientCodes = Get-Content "C:\clients\clientcodes.txt" | ForEach-Object { $_.Trim() }

foreach ($dwhDocument in $dwhDocumentsSource){
    $hasMatch = $clientCodes | Where-Object { $dwhDocument.Basename -like "*$_*" }
    if ($hasMatch) {
        Write-Output "Yes its there: $($dwhDocument.Name)"
    }
    else {
        Write-Output "No its not there: $($dwhDocument.Name)"
    }
}

方案2:正则批量匹配(效率高,适合编码量多的场景)

$dwhDocumentsSource = Get-ChildItem "C:\source\documents" -Filter *.edi
# 转义正则特殊字符,避免编码含特殊符号时匹配出错
$clientCodes = Get-Content "C:\clients\clientcodes.txt" | ForEach-Object { [regex]::Escape($_.Trim()) }
# 拼接为或匹配正则规则
$matchRule = $clientCodes -join '|'

foreach ($dwhDocument in $dwhDocumentsSource){
    if ($dwhDocument.Basename -match $matchRule) {
        Write-Output "Yes its there: $($dwhDocument.Name)"
    }
    else {
        Write-Output "No its not there: $($dwhDocument.Name)"
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 20:27:02