如何修改.cmd文件以循环浏览项目?

时间:2016-06-04 17:00:12

标签: shell for-loop cmd

我在网上找到了一个.cmd文件来做我想做的事,但它一次只能做一个项目,所以我必须创建多个文件才能完成每个项目。

看起来像这样:

@echo off
set ITEM=
set TASKBAR=
set USAGE=

set ITEM=/item:"%windir%\System32\calc.exe"
set TASKBAR=/taskbar
:: set USAGE=/?

echo on
:: Pin to Taskbar
cscript //nologo PinItem.wsf %ITEM% %TASKBAR% %USAGE%

这会将计算器固定到Windows任务栏,但是如果我还要将记事本,IE,MS Paint ...固定到任务栏,我将不得不修改脚本并保存多个副本以执行不同的操作项目

所以我的问题是:如何改进脚本以循环遍历多个项目,例如:

set ITEM={ /item:"%windir%\System32\calc.exe" ,
           /item:"%windir%\System32\notepad.exe" ,
           /item:"%windir%\System32\mspaint.exe" }

然后在%ITEM%上执行for .. next循环?

我不知道这种脚本语言,我想必须有一种方法,正确的语法是什么?

1 个答案:

答案 0 :(得分:1)

请注意,cscript命令行仅用于调试目的;删除ECHO以使其正常运行,而不是调试。

@echo off
set "ITEM="
set "TASKBAR="
set "USAGE="

    rem make sure that there is no blank space after the caret
    rem                                     here ↓  
set ITEM=/item:"%windir%\System32\calc.exe"    ,^
         /item:"%windir%\System32\notepad.exe" ,^
         /item:"%windir%\System32\mspaint.exe"    

set TASKBAR=/taskbar
:: set USAGE=/?

rem echo on
:: Pin to Taskbar
for %%G in (%ITEM%) do (
    ECHO cscript //nologo PinItem.wsf %%G %TASKBAR% %USAGE%
)

另一种方法,可能更直观:

@echo off
SETLOCAL EnableExtensions
rem ↓     ↓  note double quotes
set "ITEM="
set "ITEM=%ITEM%, "%windir%\System32\calc.exe""
set "ITEM=%ITEM%, "%windir%\System32\notepad.exe""
set "ITEM=%ITEM%, "%windir%\System32\mspaint.exe""
rem ↑             ↑                             ↑↑ note double quotes

rem echo on
:: Pin to Taskbar
for %%G in (%ITEM%) do (
    ECHO cscript //nologo PinItem.wsf /item:"%%~G" /taskbar
)

资源(必读):