# -*- coding: utf-8 -*- r'''修 verify_all.ps1 里"管道后读 $LASTEXITCODE"的写法。 问题模式: & python xxx.py 2>&1 | Select-Object -Last 4 Record "某阶段" ($LASTEXITCODE -eq 0) <-- 拿到的不一定是那条命令的码 后果: 测试**实际全过了**(输出里能看到"通过 N 项,失败 0 项"), 但 Record 记成 FAIL,汇总表一片红,真实的失败反而被淹没。 正确写法(文件里前半段已经有几处是对的): $stageOut = & python xxx.py 2>&1 $stageCode = $LASTEXITCODE $stageOut | Select-Object -Last 4 Record "某阶段" ($stageCode -eq 0) 这个脚本按上面的模式做机械替换,改完复核 + 补 BOM。 ''' from __future__ import annotations import re import sys from pathlib import Path VERIFY = (Path(r"C:\Users\shu\Desktop\deepseekagent\LanRemote") / "_tests" / "verify_all.ps1") BOM = b"\xef\xbb\xbf" def main() -> int: raw = VERIFY.read_bytes() text = raw.decode("utf-8-sig") lines = text.split("\n") out = [] index = 0 fixed = 0 # 匹配: & ... | Select-Object -Last # 下一行:Record "<名字>" ($LASTEXITCODE -eq 0) pipe_re = re.compile(r"^(\s*)& (.+?) \| Select-Object -Last (\d+)\s*$") record_re = re.compile( r'^(\s*)Record "([^"]+)" \(\$LASTEXITCODE -eq 0\)\s*$') while index < len(lines): line = lines[index] match = pipe_re.match(line) if match and index + 1 < len(lines): nxt = record_re.match(lines[index + 1]) if nxt and match.group(1) == nxt.group(1): indent = match.group(1) command = match.group(2) count = match.group(3) name = nxt.group(2) out.append("%s$stageOut = & %s" % (indent, command)) out.append("%s$stageCode = $LASTEXITCODE" % indent) out.append("%s$stageOut | Select-Object -Last %s" % (indent, count)) out.append('%sRecord "%s" ($stageCode -eq 0)' % (indent, name)) fixed += 1 index += 2 continue out.append(line) index += 1 new_text = "\n".join(out) if fixed == 0: print(" 没有要改的") return 0 VERIFY.write_bytes(BOM + new_text.encode("utf-8")) print(" 改了 %d 处" % fixed) print() # 复核:不该再有管道后直接读 $LASTEXITCODE 的 remaining = [] new_lines = new_text.split("\n") for i, l in enumerate(new_lines): if "$LASTEXITCODE" in l and "Record" in l: remaining.append(i + 1) print(" 复核:") if remaining: print(" 还有 %d 行 Record 直接读 $LASTEXITCODE: %s" % (len(remaining), remaining)) else: print(" 没有 Record 直接读 $LASTEXITCODE 了 ✓") print() print(" BOM: %s" % ("有 ✓" if VERIFY.read_bytes().startswith(BOM) else "缺!")) return 0 if __name__ == "__main__": sys.exit(main())