Rem in windows cmd

rem rem

Записывает комментарии в скрипт, пакет или файл config.sys. Records comments in a script, batch, or config.sys file. Если комментарий не указан, REM добавляется пробел по вертикали. If no comment is specified, rem adds vertical spacing.

Синтаксис Syntax

Параметры Parameters

Параметр Parameter Описание Description
Указывает строку символов, включаемую в качестве комментария. Specifies a string of characters to include as a comment.
/? /? Отображение справки в командной строке. Displays help at the command prompt.

Комментарии Remarks

Команда REM не отображает комментарии на экране. The rem command doesn’t display comments on the screen. Чтобы отобразить комментарии на экране, необходимо включить команду echo on в файл. To display comments on the screen, you must include the echo on command in your file.

В комментариях пакетного файла нельзя использовать символ перенаправления (или > ) или pipe ( | ). You can’t use a redirection character ( or > ) or pipe ( | ) in a batch file comment.

Несмотря на то, что можно использовать REM без комментариев для добавления вертикальных пробелов в пакетный файл, можно также использовать пустые строки. Although you can use rem without a comment to add vertical spacing to a batch file, you can also use blank lines. При обработке пакетной программы пустые строки игнорируются. Blank lines are ignored when a batch program is processed.

Примеры Examples

Чтобы добавить вертикальные пробелы через комментарии пакетного файла, введите: To add vertical spacing through batch file comments, type:

Чтобы включить пояснительный комментарий перед командой Prompt в файле config.sys, введите: To include an explanatory comment before the prompt command in a config.sys file, type:

Чтобы предоставить комментарий о том, что делает сценарий, введите: To provide a comment about what a script does, type:

Is there a command to refresh environment variables from the command prompt in Windows?

If I modify or add an environment variable I have to restart the command prompt. Is there a command I could execute that would do this without restarting CMD?

24 Answers 24

You can capture the system environment variables with a vbs script, but you need a bat script to actually change the current environment variables, so this is a combined solution.

Create a file named resetvars.vbs containing this code, and save it on the path:

create another file name resetvars.bat containing this code, same location:

When you want to refresh the environment variables, just run resetvars.bat

The two main problems I had coming up with this solution were

a. I couldn’t find a straightforward way to export environment variables from a vbs script back to the command prompt, and

b. the PATH environment variable is a concatenation of the user and the system PATH variables.

I’m not sure what the general rule is for conflicting variables between user and system, so I elected to make user override system, except in the PATH variable which is handled specifically.

I use the weird vbs+bat+temporary bat mechanism to work around the problem of exporting variables from vbs.

Note: this script does not delete variables.

This can probably be improved.

ADDED

If you need to export the environment from one cmd window to another, use this script (let’s call it exportvars.vbs ):

Run exportvars.vbs in the window you want to export from, then switch to the window you want to export to, and type:

On Windows 7/8/10, you can install Chocolatey, which has a script for this built-in.

After installing Chocolatey, just type refreshenv .

Here is what Chocolatey uses.

By design there isn’t a built in mechanism for Windows to propagate an environment variable add/change/remove to an already running cmd.exe, either from another cmd.exe or from «My Computer -> Properties ->Advanced Settings -> Environment Variables».

If you modify or add a new environment variable outside of the scope of an existing open command prompt you either need to restart the command prompt, or, manually add using SET in the existing command prompt.

The latest accepted answer shows a partial work-around by manually refreshing all the environment variables in a script. The script handles the use case of changing environment variables globally in «My Computer. Environment Variables», but if an environment variable is changed in one cmd.exe the script will not propagate it to another running cmd.exe.

I came across this answer before eventually finding an easier solution.

Simply restart explorer.exe in Task Manager.

I didn’t test, but you may also need to reopen you command prompt.

Credit to Timo Huovinen here: Node not recognized although successfully installed (if this helped you, please go give this man’s comment credit).

This works on windows 7: SET PATH=%PATH%;C:\CmdShortcuts

tested by typing echo %PATH% and it worked, fine. also set if you open a new cmd, no need for those pesky reboots any more 🙂

Use «setx» and restart cmd prompt

There is a command line tool named «setx» for this job. It’s for reading and writing env variables. The variables persist after the command window has been closed.

It «Creates or modifies environment variables in the user or system environment, without requiring programming or scripting. The setx command also retrieves the values of registry keys and writes them to text files.»

Note: variables created or modified by this tool will be available in future command windows but not in the current CMD.exe command window. So, you have to restart.

If setx is missing:

Or modify the registry

To programmatically add or modify system environment variables, add them to the HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE message with lParam set to the string «Environment«.

This allows applications, such as the shell, to pick up your updates.

Calling this function has worked for me:

The best method I came up with was to just do a Registry query. Here is my example.

In my example I did an install using a Batch file that added new environment variables. I needed to do things with this as soon as the install was complete, but was unable to spawn a new process with those new variables. I tested spawning another explorer window and called back to cmd.exe and this worked but on Vista and Windows 7, Explorer only runs as a single instance and normally as the person logged in. This would fail with automation since I need my admin creds to do things regardless of running from local system or as an administrator on the box. The limitation to this is that it does not handle things like path, this only worked on simple enviroment variables. This allowed me to use a batch to get over to a directory (with spaces) and copy in files run .exes and etc. This was written today from may resources on stackoverflow.com

Orginal Batch calls to new Batch:

testenvget.cmd SDROOT (or whatever the variable)

Also there is another method that I came up with from various different ideas. Please see below. This basically will get the newest path variable from the registry however, this will cause a number of issues beacuse the registry query is going to give variables in itself, that means everywhere there is a variable this will not work, so to combat this issue I basically double up the path. Very nasty. The more perfered method would be to do: Set Path=%Path%;C:\Program Files\Software. \

Regardless here is the new batch file, please use caution.

How to use Windows CMD pipe( | ) feature with CALL :Label command option?

I have a frustrating problem when I want to use the pipe(|) feature with the Window’s CMD shell’s CALL :Label option. I have a very small example (below): call-test.cmd and sample output.

The nub of the issue was/is to pipe the output of a CMD script to another program, for example the tee utility, or find command. For example:

Which would start the current command file at the label Label-02 and pipe the output to tee. Unfortunately using the pipe character(|) on the line with «call :label» option gives an error:

Whereas, «call example.cmd | tee example.log», works just fine.

The other IO redirection > works OK. It is just the one case when «call :label pipe(|)» is used that fails. To me it just looks like a windows bug.

Does anyone have a workaround and/or know of an explanation?

call-test output

call-test

6 Answers 6

The cause is, that a pipe starts both sides in a cmd context (both run parallel in one cmd-box), and each side is interpreted as a real command line argument, and on the cmd line labels aren’t allowed.

But you can call your function, if you restart your batch.

EDIT: The complete sample

0″ :Label-02 param Fails when you try to use it. While I could and did try jumping to a label manually with a GOTO, it is a hack and it would be better to have a second .CMD script. (Which is the thing I want to avoid here). – will Nov 25 ’10 at 21:34

I realize this comes a bit late, but might be helpful for others. this isn’t quite a hack, more a workaround. Or pretty «nice hack» if you must. I’m using the following solution to a similar problem:

The nice thing about it is that I can copy-paste the «header» into any batch script I need to run it in. I didn’t bother to make it recursive-safe as I didn’t needed it, so make sure you test that scenario before putting it in. Obviously, I have wrapper functions on these debug* calls, so that I don’t carry around the log file with each call. Also, in my debug log calls, I also test for the debug flag, so the wrapper itself has some more logic to it, which mainly depends on the script used in.

The obvious workaround is to redirect output of call to temporary file, use it as an input for find/tee, then delete file:

This is a more succinct version of jebs answer.

It uses the same goto technique, but instead of passing a unique «START» parameter when re-entering, it tests if the first character of the first parameter is «:» using a substring extraction and only calls goto if it’s a label. This simplifies the call, however you can’t use substring extraction with %1 variables or empty/non-existent variables so it has to use a temporary variable that always contains a value. It needs the temp var anyway to remember the label as SHIFT /1 will remove the first :LABEL parameter, but it only has to use SHIFT once, and doesn’t require an extra parameter at the call site.

[update: must do shift /1 to avoid changing %0 in case it’s used by the script]

So the following script shows how you can use the parameters passed to the original script, as well as re-entering to process labels:

the echo (bar) line being stripped by the pipe to findstr

Arrays, linked lists and other data structures in cmd.exe (batch) script

I was playing with cmd.exe, but in its help I didn’t find any info, how to define arrays.

I have found, how to define simple variables:

But, I want to create arrays, linked list etc.

So, does it able in cmd.exe ( I mean: does in cmd.exe exist any array keywords? )

I want to realize some algorithms as:

So, I also want to know, does Cmd.exe have references or instances, structs etc?

Cause its help not full in: /?

Could Cmd.exe be defined as full by Turing-Machine definition? ( Turing-Complete )

10 Answers 10

Ok. I’ll try to be as clear as possible to not be misunderstood.

In Windows Batch files a variable name should begin with a letter and may include any valid character, where valid characters are: #$'()*+,-.?@[]_`<>

besides letters and digits.

This means that from the cmd.exe point of view, SET NORMAL_NAME=123 is exactly the same as SET A#$'()*+,-.?@[\]_<>

=123 and also the same as SET VECTOR[1]=123 ; all three are normal variables. This way, it is up to you to write variable names in the form of array elements:

This way, echo %elem[2]% will show Second one .

If you want to use another variable as index, you must know that the replacement of variables enclosed in percent symbols by their values is parsed from left to right; this means that:

doesn’t give the desired result because it means: show the value of the elem[ variable, followed by i , followed by the value of the ] variable.

To solve this problem you must use Delayed Expansion, that is, insert setlocal EnableDelayedExpansion command at the beginning, enclose index variables in percent symbols, and enclose the array elements in exclamation marks:

You may also use parameters of FOR commands as indexes: for /L %%i in (1,1,3) do echo !elem[%%i]! . You must use !index! to store values in array elements when the index is changed inside a FOR or IF: set elem[!index!]=New value . To get the value of an element when the index changes inside FOR/IF, enclose the element in double percent symbols and precede the command with call . For example, to move a range of array elements four places to the left:

Another way to achieve the previous process is to use an additional FOR command to change the delayed expansion of the index by an equivalent replaceable parameter, and then use the delayed expansion for the array element. This method runs faster than previous CALL:

This way, the Batch file behaves like it manages arrays. I think the important point here is not to discuss if Batch manages arrays or not, but the fact that you may manage arrays in Batch files in an equivalent way of other programming languages.

Note that index values are not limited to numbers, but they may be any string that contain valid characters; this point allows to define what in other programming languages are called associative arrays. At this answer there is a detailed explanation of the method used to solve a problem using an associative array. Note also that the space is a valid character in variable names, so you must pay attention to not insert spaces in variable names that may go unnoticed.

I elaborated on the reasons I have to use array notation in Batch files at this post.

In this post there is a Batch file that reads a text file and stores the indexes of the lines in a vector, then does a Buble Sort of vector elements based on line contents; the equivalent result is a sort over file contents.

In this post there is a basic Relational Data Base application in Batch based on indexes stored in files.

In this post there is a complete multiple linked-list application in Batch that assembles a large data structure taken from a subdirectory and displays it in the form of TREE command.

Читайте также:  Denwer для mac os
Оцените статью