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

如何修改PowerShell脚本筛选首字母A-O且后缀为.csv的文件

解决方法

你的测试文件M_K_O_X.CSV没被匹配到,核心问题是通配符模式写错了——原模式[a-oA-O]*.*.CSV里的.*是多余的,它会要求文件名里至少有两个点(比如A.test.CSV),但你的测试文件只有一个点,自然匹配不上。

下面给你几个可行的修正方案:

方案1:直接用Get-ChildItem的筛选参数(最高效)

直接在Get-ChildItem里用-Filter参数让文件系统直接筛选,比管道过滤更快:

cd 'A:\P\E\D'
# 筛选首字母A-O(不区分大小写)、后缀为csv的文件
$files = Get-ChildItem -Path . -Recurse -Filter "[A-O]*.csv"

ForEach ($file in $files) {
    (Get-Content $file -Raw) | ForEach-Object { 
      # 这里写你的处理代码
    } | Set-Content $file
}

Windows文件系统的通配符默认不区分大小写,所以[A-O]*.csv会自动匹配首字母小写a-o的文件,不用额外写[a-oA-O]。

方案2:修正Where-Object的匹配模式

如果坚持用管道过滤,把多余的.*删掉即可:

cd 'A:\P\E\D'
$files = Get-ChildItem . -Recurse | Where-Object { $_.Name -like "[A-O]*.csv" }

ForEach ($file in $files) {
    (Get-Content $file -Raw) | ForEach-Object { 
      # 这里写你的处理代码
    } | Set-Content $file
}

方案3:精准判断首字母和后缀(无歧义)

如果担心通配符的歧义,可以分开判断首字母范围和文件后缀:

cd 'A:\P\E\D'
$files = Get-ChildItem . -Recurse -File | Where-Object { 
    # 取文件名的第一个字符
    $firstChar = $_.Name[0]
    # 判断首字母在A-O或a-o之间,且后缀是.csv
    ($firstChar -ge 'A' -and $firstChar -le 'O') -or ($firstChar -ge 'a' -and $firstChar -le 'o')
    -and $_.Extension -eq '.csv'
}

ForEach ($file in $files) {
    (Get-Content $file -Raw) | ForEach-Object { 
      # 这里写你的处理代码
    } | Set-Content $file
}

加上-File参数可以排除文件夹,避免误处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:35:22