不得不说Windows batch脚本是我见过的最差劲的脚本,没有之一。
先上一段最近解决的几个小问题的demo代码,包括:
1,赋值变量为其他进程的输出
2,For循环语句计算数列
3,For循环拆分字符串
4,For循环处理文件
5,For循环处理进程输出
@echo off
setlocal enabledelayedexpansion
:: set a variable using the output of process
tasklist | findstr "explorer.exe" > result.txt
set /p FF=<result.txt
echo %FF%
:: for statement in numbers
set total=0
for /l %%i in (1,1,5) do (
set a=%%i
echo !a!
set /a total=!total! + !a!
)
echo total=%total%
:: for statement in strings
for /f "tokens=1,2* delims=_" %%i in ("test_argument_12345") do (
echo %%i
echo %%j
echo %%k
)
:: for statement using wildcard, shouldn't use /f option
for %%G in (*.bat *.txt) do echo %%G
:: for statement in files
for /f "tokens=1,2*" %%i in (result.txt) do (
set ti=%%i
echo !ti!
echo %%j
echo %%k
)
:: for statement with command output
for /f "tokens=1,2*" %%i in ('"tasklist | findstr "explorer.exe""') do (
set ti=%%i
echo !ti!
echo %%j
echo %%k
)
endlocal