如何让Get-ChildItem在文件夹结构中匹配文件名前缀?
改PowerShell脚本实现按文件名前缀匹配复制
原脚本是精确匹配完整文件名,现在要改成按前缀查找并复制文件,直接看修改后的代码和关键点:
修改后的完整脚本
# 源目录和目标目录 $source = "C:\Data_Files\Source" $destination = "C:\Data_Files\Output" # 读取input里的前缀列表 $prefixList = Get-Content "C:\Data_Files\Input.txt" # 逐个处理每个前缀 foreach ($prefix in $prefixList) { # 直接递归搜索所有以当前前缀开头的文件 $matchingFiles = Get-ChildItem $source -Recurse -File -Filter "$prefix*" foreach ($file in $matchingFiles) { $targetPath = Join-Path -Path $destination -ChildPath $file.Name # 目标目录不存在该文件时才复制 if (-not (Test-Path -Path $targetPath)) { Copy-Item -Path $file.FullName -Destination $destination -Verbose } } }
关键改动说明
- 前缀匹配实现:用
Get-ChildItem的-Filter "$prefix*"通配符直接筛选前缀匹配的文件,比原脚本遍历所有文件再判断效率高得多,还能避免遗漏。 - 精准筛选文件:新增
-File参数,确保只处理文件(排除目录),解决原脚本可能误处理目录的问题。 - 路径拼接优化:用
Join-Path替代手动拼接路径,避免因路径分隔符写错导致的错误。 - 逻辑简化:去掉原脚本的两层嵌套循环,直接获取匹配文件后处理,代码更简洁易读。
额外实用小技巧
- 如果input.txt里有空行或无效内容,可以添加过滤逻辑:
$prefixList = Get-Content "C:\Data_Files\Input.txt" | Where-Object { $_ -match '\S' },自动跳过空行。 - 若需要严格区分文件名大小写(Windows默认不区分),可以把筛选逻辑改成字符串方法:
Get-ChildItem $source -Recurse -File | Where-Object { $_.Name.StartsWith($prefix, [System.StringComparison]::Ordinal) }
内容的提问来源于stack exchange,提问作者Andy
相关产品推荐
相关产品推荐

