using CMD and batch scripting, how can I give in my batch script a command line argument like /user=something and then how to get this value inside the script ? I tried the below simple script but it does not work. The script is:
@echo off
setlocal
REM Loop through each command-line argument
for %%A in (%*) do (
REM Check if the argument starts with "/user="
if /i "%%A"=="%A:/user=*" (
REM Extract the value after "/user="
set "user=%%A:~6%"
)
)
REM Check if the user variable was set and display it
if defined user (
echo User is %user%
) else (
echo No user argument was provided
)
The result was: No user argument was provided
How can accomplish it ? Thanks
There's some things to keep in mind when parsing arguments using a plain For:
' ',
' '=
' ';
'?
' and '*
' are wildcards of the for command and will result in undesired behaviour if provided by the user.^
' '&
' '>
' '<
' '|
' '!
' and '%
' are considered poison characters and can likewise result in unintended behaviour and / or code execution.All that said, if the input can be trusted, what your aiming for can be done by using a variable and it's defined status to effect a switch statement when the /User string is encountered.
@echo off
Setlocal EnableExtensions
Set "UserArg="
For %%G in (%*)do (
If defined UserArg (
Set "UserArg="
Set "User=%%~G"
)
If /i "%%G" == "/User" Set "UserArg=1"
)
Echo(%User%
Pause
Endlocal & Goto:eof