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

PowerShell脚本输出重复优先级行号不准确,寻求修复帮助

问题:PowerShell脚本检测重复优先级时行号不准确

我正在编写PowerShell脚本,需求是当规则的**Priority(优先级)**与上一条(上方)规则重复时,将对应行输出至控制台。但测试后发现输出的重复优先级行号并不准确,代码和输出如下:

原代码

# Load the Excel file
$designSheet = " /home/lokeshdir/designsheet.xlsx"
$excel = Import-Excel -Path $designSheet
# Iterate through the rows and check for duplicated priorities
for ($i = 1; $i -lt $excel.Count; $i++) {
    $currentRow = $excel[$i]
    $currentPriority = $currentRow.Priority

    $previousRow = $excel[$i - 1]
    $previousPriority = $previousRow.Priority

    if ($currentPriority -eq $previousPriority) {
        Write-Host "Row $($i + 1) has a duplicated priority value."
        # Output additional information or actions if needed
    }
}

原输出

PS /home/lokeshdir> ./NSGRulesvalidation.ps1 
Row 11 has a duplicated priority value.
Row 18 has a duplicated priority value.
PS /home/lokeshdir> 

补充说明

实际需求是结合**Direction(入站/出站)**判断重复:仅当同一Direction下的Priority与上一行重复时,才判定为问题(对应参考截图中红色框标记的内容,绿色框为原始值)。原脚本未考虑Direction维度,且行号计算存在误差。


修复方案

问题根源

  1. 行号计算偏差:Import-Excel返回的数组从索引0开始,若Excel包含表头行,数组索引对应的实际行号需额外加1;原代码的$i + 1未适配表头行的存在,导致行号不准确。
  2. 缺少维度判断:仅对比Priority未结合Direction,不符合实际需求的重复判定逻辑。

修复后的代码

# 加载Excel文件(清理路径多余空格)
$designSheet = "/home/lokeshdir/designsheet.xlsx"
$excel = Import-Excel -Path $designSheet

# 遍历数据行(索引从1开始,对应Excel第2行,假设第1行是表头)
for ($i = 1; $i -lt $excel.Count; $i++) {
    $currentRow = $excel[$i]
    $currentPriority = $currentRow.Priority
    $currentDirection = $currentRow.Direction

    $previousRow = $excel[$i - 1]
    $previousPriority = $previousRow.Priority
    $previousDirection = $previousRow.Direction

    # 同时校验Priority和Direction是否与上一行重复
    if ($currentPriority -eq $previousPriority -and $currentDirection -eq $previousDirection) {
        # 计算实际Excel行号:索引+2(数组索引0对应Excel第2行,表头为第1行)
        Write-Host "Row $($i + 2) has duplicated priority [$currentPriority] in direction [$currentDirection]."
    }
}

关键修复点

  • 行号精准计算:若Excel无表头行,将行号公式改为$i + 1即可;有表头时用$i + 2匹配实际表格行号。
  • 增加Direction校验:只有当Priority和Direction同时与上一行一致时,才判定为重复,符合实际需求。
  • 清理路径空格:去除原路径开头的多余空格,避免文件加载异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 21:06:21