windows – How to set a variable in bat/cmd? – Stack Overflow

Assign command output to variable in batch file

I’m trying to assign the output of a command to a variable – as in, I’m trying to set the current flash version to a variable. I know this is wrong, but this is what I’ve tried:

set var=reg query hklmSOFTWAREMacromediaFlashPlayerCurrentVersion>

or

reg query hklmSOFTWAREMacromediaFlashPlayerCurrentVersion >> set var

Yeah, as you can see I’m a bit lost. Any and all help is appreciated!

Cmd variable name restrictions?

The only character that cannot ever appear in a user defined batch environment variable name is =. The SET statement will terminate a variable name at the first occurrence of =, and everything after will be part of the value.

It is simple to assign a variable name containing a :, but the value cannot normally be expanded except under specific circumstances.

When extensions are enabled (default behavior)

The colon is part of search/replace and substring expansion syntax, which interferes with expansion of variables containing colon in the name.

There is one exception – if the : appears as the last character in the name, then the variable can be expanded just fine, but then you cannot do search and replace or substring expansion operations on the value.

When extensions are disabled

Search/replace and substring expansion are not available, so there is nothing to stop expansion of variables containing colons from working just fine.

@echo off
setlocal enableExtensions

set "test:=[value of test:]"
set "test:more=[value of test:more]"
set "test"

echo(
echo With extensions enabled
echo -------------------------
echo %%test:%%              = %test:%
echo %%test::test=replace%% = %test::test=replace%
echo %%test::~0,4%%         = %test::~0,4%
echo %%test:more%%          = %test:more%

setlocal disableExtensions
echo(
echo With extensions disabled
echo -------------------------
echo %%test:%%     = %test:%
echo %%test:more%% = %test:more%

–OUTPUT–

test:=[value of test:]
test:more=[value of test:more]

With extensions enabled
-------------------------
%test:%              = [value of test:]
%test::test=replace% = :test=replace
%test::~0,4%         = :~0,4
%test:more%          = more

With extensions disabled
-------------------------
%test:%     = [value of test:]
%test:more% = [value of test:more]

See https://msconfig.ru/a/7970912/1012053 for a complete description of exactly how variable expansion works.

:/>  Найти ключ активации windows с помощью командной строки или power shell

How to set a variable in bat/cmd?

The reason why your variable %var% is not showing is because it is being SET inside a parenthesised code block. The usual way to prevent such an occurrence is to enable delayed expansion, and replace the % characters with !‘s.

There’s a simpler workaround, in single cases such as this, which is to invoke a CALL command:

CALL ECHO ENTERED "%%var%%"

I have decided to post this answer as an update to my comment because:

  1. SC QUERYX "%SvcName%" should be SC QUERY "%SvcName%".
  2. You can use a single FIND or even FINDSTR
  3. There’s no need to use NET when you’re already using SC.

Using FIND:

@ECHO OFF
SET "SvcName=QTCE"
SC QUERY | FIND /I "%SvcName%" > NUL && (
    ECHO %SvcName% is running
    ECHO=
    ECHO What do you want to do?
    ECHO=
    ECHO 1 - RESTART QTCE
    ECHO 2 - STOP QTCE
    ECHO=
    SET /P "var=Type 1, 2 then press ENTER: "
    CALL ECHO ENTERED "%%var%%"
    ECHO Done! You're welcome ..
) || (
    ECHO %SvcName% is not running
    ECHO=
    ECHO Don't worry! We'll start it now!
    IF /I "%SvcName%"=="QTCE" SC START QSERVER
    SC START %SvcName%
    ECHO=
    ECHO "%SvcName%" is started
)
PAUSE

To use FINDSTR instead replace line 3 above with:

SC QUERY "%SvcName%" | FINDSTR /RC:"STATE.*: 4" >NUL && (

Note
The above does not fix the other issues with your code, starting services which you haven’t checked the status of and informing the end user a service has been started without checking that it has. Also depending upon how you expand the code, you can only restart a service which is paused, and not pending a continue.

:/>  Как изменить настройки word 2010 по умолчанию

EDIT
As a courtesy, to your comment and my response, here’s a basic restructuring of your script, which prevents the need to use delayed expansion, by not SETting and using %var% within a parenthesised code block.

@ECHO OFF
SET "SvcName=QTCE"

SC QUERY | FIND /I "%SvcName%" > NUL || GOTO SVCSTART

ECHO %SvcName% is running
ECHO=
ECHO What do you want to do?
ECHO=
ECHO 1 - RESTART %SvcName%
ECHO 2 - STOP %SvcName%
ECHO=
SET /P "var=Type 1, 2 then press ENTER: "
ECHO ENTERED "%var%"
ECHO Done! You're welcome ..
PAUSE
GOTO :EOF

:SVCSTART
ECHO %SvcName% is not running
ECHO=
ECHO Don't worry! We'll start it now!
IF /I "%SvcName%"=="QTCE" SC START QSERVER
SC START %SvcName%
ECHO=
ECHO "%SvcName%" is started
PAUSE
GOTO :EOF

Пример глобальной переменной (global variables):

Переменные объявлены в файле Batch, и не находятся в блоке команд setlocal .. endlocal, будут глобальными переменными. Они могут быть использованы в других файлах в одном и том же сеансе работы (Session).

В данном примере у нас есть 2 файла batchFile1.bat и batchFile2.bat. Переменная MY_ENVIRONMENT определяется в файле 1, и используется в файле 2.


Открыть окно CMD, и CD к папке содрежащей файл batchFile1.bat, batchFile2.bat, запустить поочередно каждый файл.

Windows позволяет вам создать переменные среды, данные переменные будут глобальными переменными, которые можно использовать в любых файлах batch.

В Windows выберите:

  • Start Menu/Control Panel/System
  • Advanced (Tab) > Environment Variables..

Пример локальной переменной (local variables)


Локальные переменные (Local variable) объявлены в блоке, начинаются с setlocal и заканчиваются на endlocal.

Оставьте комментарий