1

I want to create a shortcut based on the windows username via a batch file

i was thinking along the lines of:

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

I'm having issues with the first part as I already know how to create shortcuts via command line...

Hope I can find some help.

3 Answers 3

5

There is not really an array type in batch files, but we can fudge it by iterating over a space-separated list with 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))

If Robby is logged in, output is:

Not found
Not found
Robby is found
Not found
Sign up to request clarification or add additional context in comments.

2 Comments

Does not work for me (on Windows 7). I get the following error: "arrayi" kann syntaktisch an dieser Stelle nicht verarbeitet werden.
Changing to for %%i in (%array%) do (if %%i==%USERNAME% (echo %USERNAME% is found) else (echo %USERNAME% not found)) made it working
2

example:

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

some more code to get it more clearly:

@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

.. output is:

Jimmy is in the array.
Paul is NOT in the array.

Comments

0
@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...

1 Comment

whoa... will the downvoters please tell me where I went wrong? please comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.