批处理可读性不会影响执行variables

我目前正在编写一个性能助手,写日常的人可以阅读和编辑它。 我的问题是,是否有可能优化批处理代码而不影响其可读性? 下面是我所拥有的一小段代码:

for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j if "%version%" == "10.0" SET WinX10=1 if "%version%" == "6.3" SET WinX81=1 if "%version%" == "6.2" SET WinX80=1 if "%version%" == "6.1" SET WinX7=1 if "%version%" == "6.0" SET WinXVista=1 if "%version%" == "5.2" SET WinXXP64=1 if "%version%" == "5.1" SET WinXXP32=1 goto OSScanFinder rem Scans your OS for version specific files, required for Extreme, Gaming, and Boot :OSScanFinder if defined WinX10 goto BootCleanWindows10Latest if defined WinX81 goto BootCleanWindows81 if defined WinX80 goto BootCleanWindows80 if defined WinX7 goto BootCleanWindowsSeven if defined WinXVista goto BootCleanVista if defined WinXXP64 goto BootCleanXP64 if defined WinXXP32 goto BootCleanXP32 @echo Couldn't find your Operating System. @echo I don't support Win2000, Windows Server 2003/R2/2008/R2/2012/R2 @echo Try running as administrator. If that doesn't work, please contact me at the address provided inside of the .bat file. pause exit 

 rem Chrome if exist "C:\Program Files (x86)\Google\Chrome\Application\Chrome.exe" SET ChromeYes=Defined rem uTorrent if exist "%userprofile%\Downloads\utorrent.exe" SET uTorrentYes=Defined if defined ChromeYes TASKKILL /im Chrome.exe /f if defined uTorrentYes TASKKILL /im utorrent.exe /f 

我不是要求某人优化我的代码,只要有更好的写法,或者在保持可读性的同时使用“IF DEFINED”和“SET”更好。

可读性是一个抽象概念,因此是个人偏好的问题。 例如, 在我看来 ,在你的代码中,你用不同的方式做了两次相同的问题,所以这是不必要的复杂的。 你可以做这样的事情:

 for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j if "%version%" == "10.0" goto BootCleanWindows10Latest if "%version%" == "6.3" goto BootCleanWindows81 if "%version%" == "6.2" goto BootCleanWindows80 if "%version%" == "6.1" goto BootCleanWindowsSeven if "%version%" == "6.0" goto BootCleanVista if "%version%" == "5.2" goto BootCleanXP64 if "%version%" == "5.1" goto BootCleanXP32 @echo Couldn't find your Operating System. @echo I don't support Win2000, Windows server 2003/R2/2008/R2/2012/R2 @echo Try running as administrator. If that doesn't work, please contact me at the address provided inside of the .bat file. pause exit 

然而, 在我看来 ,较短的代码总是更容易阅读和理解,所以它更具可读性 。 我会这样写代码:

 for /f "tokens=4-5 delims=. " %%i in ('ver') do set VERSION=%%i.%%j call Version-%version% if errorlevel 1 ( @echo Couldn't find your Operating System. @echo I don't support Win2000, Windows server 2003/R2/2008/R2/2012/R2 @echo Try running as administrator. If that doesn't work, please contact me at the address provided inside of the .bat file. ) pause exit 

…并将文档添加到每个代码段中:

 :Version-10.0 WinX10 BootCleanWindows10Latest rem Apropriate code here exit /B :Version-6.3 WinX81 BootCleanWindows81 rem Apropriate code here exit /B ... etc, until :Version-5.1 WinXXP32 BootCleanXP32 rem Apropriate code here exit /B