Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running variable string as command in batch scripting [closed]

EDIT: There was nothing wrong with the code below. The error was coming from elsewhere.

The command variable is the command I want to execute. The name variable is pulling a list of computer names. When I echo !command! it returns the value I want to use. That should run the command needed to delete all of the machines, however, when I actually run !command! or %command%, the name variable isn't added and it fails.

d:
cd "Program Files\admin"
setlocal EnableDelayedExpansion
SET string=%
for /f "tokens=*" %%a in (oldMachines.txt) do (
set name=%%a
set command=sbadmcl.exe AdminUser:admin -AdminPwd:password -Command:DeleteMachine -Machine:!name!
REM echo !name!
REM echo !command!
REM !command!
%command%
)
pause
like image 860
spassen Avatar asked Jul 27 '12 15:07

spassen


People also ask

Why is %% used in batch file?

%% in batch acted like \\ in bash. Where one would need to cancel the meaning of the previous percent-sign in a batch file; because variables in batch look like %var% . So because percent had a special meaning you needed to use %%var%% so a variable was still usable in a batch file.

How do I stop a script from closing in CMD?

If you want the command prompt cmd widnow to stay open after executing the last command in batch file –you should write cmd /k command at the end of your batch file. This command will prevent the command prompt window from closing and you'll get the prompt back for giving more commands in the cmd window.

What does @echo off do?

The ECHO-ON and ECHO-OFF commands are used to enable and disable the echoing, or displaying on the screen, of characters entered at the keyboard. If echoing is disabled, input will not appear on the terminal screen as it is typed. By default, echoing is enabled.


1 Answers

%command% will not work because it is expanded at parse time, so the expanded value is the value of command prior to the loop executing.

I don't know why !command! does not work. Normally you want to use normal expansion instead of delayed expansion when executing code in a variable because delayed expansion limits some of the operations you can do. It has to do with how the CMD parser works. But I don't see anything in your command that should cause problems with delayed expansion.

Try call %%command%%

like image 114
dbenham Avatar answered Nov 02 '22 21:11

dbenham