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

批处理脚本返回重复结果问题求助

批处理脚本返回重复结果问题求助

嗨,Tyler!我一眼就看穿问题所在啦~你的脚本之所以会重复输出那两行内容,核心原因是wmic命令的输出格式在被for /f解析时会产生额外的空白行。

wmic默认用Unicode编码输出内容,当for /f读取并转换为ANSI格式后,会莫名多出一个空行。你的for /f循环只跳过了第一行的表头,但没过滤掉后面的空行,导致循环会多执行一次——空变量配合echo输出,就会重复显示前面的提示文本,看起来像是结果被打印了两次。

给你两种简单有效的解决办法,选你顺手的用就行:

方法1:用findstr过滤空行

修改两个for /f循环,在wmic命令后面加个管道过滤掉空行,直接从源头上避免空行进入循环:

@echo off

:beginning

set /p computerName=Enter the computer name:

for /f "skip=1 delims=" %%i in ('wmic /node:"%computerName%" computersystem get username ^| findstr /r /v "^$"') do (
    echo User logged on to %computerName% is: %%i
)

for /f "skip=1 delims=" %%j in ('wmic /node:"%computerName%" bios get serialnumber ^| findstr /r /v "^$"') do (
    echo Serial number of %computerName% is: %%j
)

echo.

:menu
echo Choose one of the following options:
echo 1. Run the script again
echo 2. Turn to command prompt
echo.
set /p menuOption=Enter your choice:

if "%menuOption%"=="1" goto beginning
if "%menuOption%"=="2" goto end

:end
cmd /k

(顺便帮你修正了脚本里的跳转小问题:原来的goto start和goto main是多余的,直接跳回:beginning就能重新执行啦)

方法2:在循环内判断变量是否为空

如果你不想加管道命令,也可以在循环里检查变量有没有实际内容,只有非空时才执行echo:

for /f "skip=1 delims=" %%i in ('wmic /node:"%computerName%" computersystem get username') do (
    if not "%%i"=="" echo User logged on to %computerName% is: %%i
)

for /f "skip=1 delims=" %%j in ('wmic /node:"%computerName%" bios get serialnumber') do (
    if not "%%j"=="" echo Serial number of %computerName% is: %%j
)

两种方法都能完美解决重复输出的问题,你可以试试看~

备注:内容来源于stack exchange,提问作者Tyler

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 13:57:48