批处理脚本检测命令行程序双字符串输出异常求助
问题分析与解决
你的脚本挂起的核心原因是管道传递输出的方式错误:第一个find命令只输出匹配到的设备行,第二个find命令从管道读取这些内容,但找不到</LiveTV,且因管道输入未正确终止导致挂起。同时引号转义虽无大问题,但逻辑上需要先确认设备存在,再检查是否在使用。
修正后的脚本
@echo off title Tuner Indicator set "tempFile=%temp%\tuner_status.tmp" :begin :: 切换到目标目录(/d确保跨盘符切换) cd /d "C:\Program Files\NextPVR" :: 将NScriptHelper的输出保存到临时文件 NScriptHelper.exe -server:127.0.0.1:8866 -status > "%tempFile%" :: 第一步:检查目标调谐器是否存在 find /i "identifier=""Silicondust HDHomeRun Tuner 1045D3F7-0 (#0)""" "%tempFile%" >nul if errorlevel 1 ( echo Tuner 1 not detected goto cleanup ) :: 第二步:检查调谐器是否在使用 find /i "</LiveTV" "%tempFile%" >nul if errorlevel 0 ( echo Tuner 1 in use ) else ( echo Tuner 1 not in use ) :cleanup :: 删除临时文件(避免残留) del "%tempFile%" >nul 2>&1 :: 延迟1秒再循环(可选,减少资源占用) timeout /t 1 /nobreak >nul goto begin
关键修改说明
- 使用临时文件存储输出:避免管道过滤导致的输入截断问题,让两个
find命令都能读取完整的输出内容。 - 分两步判断逻辑:先确认调谐器设备存在,再检查是否有
LiveTV行,避免误判。 - 添加
cd /d参数:确保即使当前盘符不是C盘,也能正确切换到目标目录。 - 增加延迟(可选):
timeout命令减少循环频率,降低系统资源消耗。 - 引号转义正确保留:
identifier=""Silicondust..."""的写法在批处理中会被解析为identifier="Silicondust...",符合匹配需求。
替代方案(无需临时文件)
如果不想用临时文件,可以通过两次调用NScriptHelper(或用for /f捕获输出),但效率略低:
@echo off title Tuner Indicator set "nscriptCmd=C:\Program Files\NextPVR\NScriptHelper.exe -server:127.0.0.1:8866 -status" :begin :: 检查设备是否存在 %nscriptCmd% | find /i "identifier=""Silicondust HDHomeRun Tuner 1045D3F7-0 (#0)""" >nul if errorlevel 1 ( echo Tuner 1 not detected goto delay ) :: 检查是否在使用 %nscriptCmd% | find /i "</LiveTV" >nul if errorlevel 0 ( echo Tuner 1 in use ) else ( echo Tuner 1 not in use ) :delay timeout /t 1 /nobreak >nul goto begin
内容的提问来源于stack exchange,提问作者user2860253
相关产品推荐
相关产品推荐

