在数组中查找变量 - 批处理



我想通过批处理文件根据Windows用户名创建一个快捷方式

我的想法是:

if %username% in (a,b,c,d) (
    shortcut ShortcutName DestinationPath
)
else (
    shortcut OtherShortcutName OtherDestinationPath
)

我在第一部分遇到问题,因为我已经知道如何通过命令行创建快捷方式......

希望我能找到一些帮助。

批处理文件中实际上没有数组类型,但我们可以通过迭代一个空格分隔的列表来捏造它,for

@ECHO OFF
set Array=Peter James Robby Jimmy
for %i in (%array%) do (if %i==%USERNAME% (echo %USERNAME% is found) else (echo %USERNAME% not found))

如果 Robby 已登录,则输出为:

Not found
Not found
Robby is found
Not found

示例:

@ECHO OFF &SETLOCAL 
if defined Array[%username%] (
    shortcut ShortcutName DestinationPath
) else (
    shortcut OtherShortcutName OtherDestinationPath
)

更多代码以更清楚地获得它:

@ECHO OFF &SETLOCAL 
set "Array[Peter]=true"
set "Array[James]=true"
set "Array[Robby]=true"
set "Array[Jimmy]=true"
set "MyUserName=Jimmy"
call:check "%MyUserName%"
set "MyUserName=Paul"
call:check "%MyUserName%"
goto:eof
:check
if defined Array[%~1] (
    echo %~1 is in the array.
) else (
    echo %~1 is NOT in the array.
)
exit /b

.. 输出为:

Jimmy is in the array.
Paul is NOT in the array.
@echo off
for %%i in (a b c d) do (^
 if %%i'==%username%' (shortcut ShortcutName DestinationPath &goto isuser)^
)
rem else
shortcut OtherShortcutName OtherDestinationPath
:isuser
rem other code...

最新更新