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

PowerShell脚本优化:匹配指定项及状态后跳转至下一个CSV条目

PowerShell脚本优化实现

需求说明

  • 仅当当前条目的Status字段匹配Despatched in Warehouse时,才记录并返回搜索命中结果
  • 针对每个CSV条目,找到第一个匹配的文件后立即停止搜索,处理下一个条目

原脚本代码

##Region ForEach Loop 
#==============================================================================
# The variable array ($array) is declared and holds an Array of strings.
$array = Import-Csv '' -Delimiter ','
$results = @()
$logFile = ''
# This is a ForEach loop block.
foreach ($item in $array) 
{
    # This echos out the present value of the string in the array when the condition is satisfied.
    # `n - it creates a new line after the message.
    # This is a print to screen CMDLET [Write-Host].
    $A= Write-Host Searching for $item.Web_Reference
    $B= Write-Host Status $item.Status
    $A + $B

    Try{
    $result += Get-ChildItem -Path '*.csv' -Recurse | Select-String $item.Web_Reference -List | Select Path
    if($result.Count -eq 0 -AND $status -Match 'Despatched in Warehouse'){continue}
    $logMessage = $item.Web_Reference + " - " + $result.Path
    $logMessage >> $logFile
    $results += $result
    }
    Catch
    {
    }
}

$results

#==============================================================================
#EndRegion ForEach Loop

优化后的脚本

##Region ForEach Loop 
#==============================================================================
# 导入目标CSV文件,替换为实际路径
$array = Import-Csv '你的源CSV路径.csv' -Delimiter ','
$results = @()
# 替换为实际日志文件路径
$logFile = '搜索结果日志.txt'

foreach ($item in $array) 
{
    Write-Host "正在搜索: $($item.Web_Reference) | 当前状态: $($item.Status)"

    Try{
        # 每次循环重置$result,避免累积之前的结果
        $result = $null
        # 使用-List参数找到第一个匹配后立即停止搜索
        $result = Get-ChildItem -Path '*.csv' -Recurse | Select-String -Pattern $item.Web_Reference -List | Select-Object -ExpandProperty Path
        
        # 仅当状态匹配指定值且找到结果时,才记录日志和结果
        if ($item.Status -eq 'Despatched in Warehouse' -and $result) {
            $logMessage = "$($item.Web_Reference) - $result"
            Add-Content -Path $logFile -Value $logMessage
            $results += [PSCustomObject]@{
                Web_Reference = $item.Web_Reference
                Status = $item.Status
                MatchedPath = $result
            }
        }
    }
    Catch{
        Write-Warning "处理$($item.Web_Reference)时出错: $_"
    }
}

# 输出最终结果
$results

#==============================================================================
#EndRegion ForEach Loop

关键修改点说明

  • 状态判断修正:原脚本未正确引用当前条目的状态字段,改为直接判断$item.Status
  • 单次搜索结果隔离:每次循环重置$result,避免不同条目结果互相干扰
  • 搜索终止逻辑:利用Select-String的-List参数,确保找到第一个匹配项后立即停止搜索,符合需求
  • 日志写入优化:使用Add-Content替代>>,更符合PowerShell最佳实践
  • 结果结构化:将结果存储为自定义对象,便于后续处理和查看
  • 错误提示增强:在Catch块中添加警告信息,便于排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 15:08:31