How-To Geek

How to use windows cmd environment variables.

Environment Variables can be set permanently for a specific user or system-wide, or they can be set temporarily for a single process.

Quick Links

How to add or modify an environment variable, how to remove an environment variable.

It is easy to add or modify an environment variable with Command Prompt (CMD), but removing one is much more complicated. Here are a few different ways you can do it.

First, you need to launch Command Prompt, or CMD, as an administrator . Click Start, type "cmd" into the search box, and then click "Run as Administrator."

Any user environment variable can be set or modified in a regular Command Prompt window, but changing system-wide environment variables requires an elevated Command Prompt.

There are two distinct ways to set environment variables.

Setting an Environment Variable Temporarily

The first uses the set command. Set defines an environment variable exclusively within the process in which it has been defined --- in other words, the variable only works in the window you have open or the script that contains it.

Here's an example: Let's say you want to create an environment variable named LifeAnswerVar and set the value to 42. The command would be

While that window is open, LifeAnswerVar will have the value 42.

When it is closed, the environment variable and its value are deleted.

The exact same method works if you want to temporarily modify an existing Windows system variable. All you need to do is substitute the system variable you want to change in place of LifeAnswerVar, and the value you want to assign in place of 42.

As an example, if you wanted to move the TMP folder to C:\Example Folder, you'd enter the command

The first line,

, shows the current value of TMP. The second line assigns TMP a new value. The third line confirms that it has changed.

Setting an Environment Variable Permanently

The second way uses setx. Setx defines Windows environment variables permanently. They persist between windows and between restarts, and are written to the Windows Registry . These environment variables can be defined for a specific user, or they can be defined for system-wide use.

The command

will create a new environment variable named ExVar1 and assign the value "Tomato" to it. The /m argument specifies that the new variable should be system-wide, not just for the current user.

Use the exact same command to modify an existing environment variable, substituting ExVar1 for the name of the variable you'd like to change.

If you use setx to modify a variable and set to view the value of the variable, set will not display the right value until a new Command Prompt window is opened.

If you want to add or modify a user environment variable, just omit the /m argument from the command.

Removing an environment variable is a bit harder than adding or modifying one.

As with adding a variable, any user environment variable can be deleted in a regular Command Prompt window, but deleting a system-wide environment variable requires an elevated Command Prompt.

Removing an Environment Variable Temporarily

If you want to temporarily remove an environment variable for the current process, like a script, PowerShell window, or Command Prompt window, you can use the set command. All you need to do is assign no value to the variable.

For example, what if you have the variable definition

in the system-wide environment variables, but wanted to ignore it for one particular process? You can type

into Command Prompt or include that line in your script. The variable will be set to nothing while the script executes or until you open a new Command Prompt window.

Removing an Environment Variable Permanently

Removing an environment variable permanently is a bit more complex --- you have to use

Reg is the command-line version of the Registry Editor. You should proceed with caution --- a typo could result in you accidentally deleting something important. It never hurts to back up the part of the registry you're editing , either.

The environment variables for individual users are stored in

. System-wide environment variables are stored elsewhere, in

Let's use the

example. The ExVar1 environment variable was defined system-wide, which means it is located in the HKEY_LOCAL_MACHINE directory rather than the HKEY_CURRENT_USER directory. Specifically, the path to the subkey is:

This path contains a space. Any time there is a space in a path entered in a command-line interface, you must use quotation marks around the path, otherwise, it is exceedingly likely that it will not execute correctly.

Now we need to use the

command to remove it. Keep in mind that you'll need to substitute your variable name for ExVar1 in the command below.

There is a lot there, so let's break it down a bit.

  • reg delete --- defines the application (reg) and command (delete) we're using
  • "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\" --- Tells reg delete where to look for the key
  • /f --- Tells reg delete to delete the key without prompting for confirmation
  • /v --- Tells reg delete that it will be given a specific subkey to delete
  • ExVar1 --- The name of the subkey we want to delete

Deleting an environment variable for an individual user is exactly the same as deleting a system-wide variable, except the path will be different. If ExVar1 were a user environment variable, the command to delete it would be:

If the command to delete the environment variable was successful, you should see "The operation completed successfully" in the Command Prompt.

Any time you remove an environment variable like this, you need to restart explorer.exe. You can restart Explorer.exe manually , or you can just restart your entire computer . Either will work, and the changes should take effect immediately after the restart.

Related: How to List Environment Variables on Linux

Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.

Variable names are not case sensitive but the contents can be.

It is good practice to avoid using any delimiter characters (spaces, commas etc) in the variable name .

Delimiter characters can be used in the value if the complete assignment is surrounded with double quotes to prevent the delimiter being interpreted.

Any extra spaces around either the variable name or the string , will not be ignored, SET is not forgiving of extra spaces like many other scripting languages. So use SET alpha=beta , not SET alpha = beta

The first character of the name must not be numeric . It is a common practice to prefix variable names with either an underscore or a dollar sign _variable or $variable , these prefixes are not required but help to prevent any confusion with the standard built-in Windows Environment variables or any other command strings.

The CMD shell will fail to read an environment variable if it contains more than 8,191 characters.

SET is an internal command. If Command Extensions are disabled all SET commands are disabled other than simple assignments like: _variable=MyText

Display a variable:

In most contexts, surround the variable name with % ’s and the variable’s value will be used e.g. To display the value of the _department variable with the ECHO command: ECHO %_department% If the variable name is not found in the current environment then SET will set %ERRORLEVEL% to 1 . This can be detected using IF ERRORLEVEL ... Including extra characters can be useful to show any white space: ECHO [%_department% ] ECHO "%_department% " Type SET without parameters to display all the current environment variables. Type SET with a variable name to display that variable SET _department The SET command invoked with a string (and no equal sign) will display a wildcard list of all matching variables Display variables that begin with 'P': SET p Display variables that begin with an underscore SET _

Set a variable:

Example of storing a text string: C:\> SET "_dept=Sales and Marketing" C:\> set _ _dept=Sales and Marketing Set a variable that contains a redirection character, note the position of the quotes which are not saved: SET "_dept=Sales & Marketing" One variable can be based on another, but this is not dynamic E.g. C:\> set "xx=fish" C:\> set "msg=%xx% chips" C:\> set msg msg=fish chips C:\> set "xx=sausage" C:\> set msg msg=fish chips C:\> set "msg=%xx% chips" C:\> set msg msg=sausage chips Avoid starting variable names with a number, this will avoid the variable being mis-interpreted as a parameter %123_myvar% < > %1 23_myvar To display undocumented system variables: SET "

Values with Spaces - using Double Quotes

There is no hard requirement to add quotation marks even when assigning a value that includes spaces: SET _variable=one two three ECHO %_variable% Adding quotation marks is a best practise and will account for any trailing spaces and special characters like '&' . The variable contents will not include the surrounding quotes: SET " _variable=one & two " ECHO "%_variable%" If you place quotation marks around just the value, then those quotes will be stored: SET _variable= "one & two" ECHO %_variable% This can be used for long filenames: SET _QuotedPath= " H:\Config files\config 64.xml " COPY %_QuotedPath% C:\Demo\final.xml Alternatively you can add quotes at the point where they are needed: SET " _Filename=config 64.xml" COPY "H:\Config files\%_Filename%" C:\Demo\final.xml

Variable names with spaces

A variable can contain spaces and also the variable name itself can contain spaces, therefore the following assignment: SET _var =MyText will create a variable called "_var " ← note the trailing space.

Prompt for user input

The /P switch allows you to set a variable equal to a line of input entered by the user. The Prompt string is displayed before the user input is read. @echo off Set /P _ans=Please enter Department: || Set _ans=NothingChosen :: remove &’s and quotes from the answer (via string replace ) Set _ans=%_ans:&=% Set _ans=%_ans:"=% If "%_ans%"=="NothingChosen" goto sub_error If /i "%_ans%"=="finance" goto sub_finance If /i "%_ans%"=="hr" goto sub_hr goto:eof :sub_finance echo You chose the finance dept goto:eof :sub_hr echo You chose the hr dept goto:eof :sub_error echo Nothing was chosen Both the Prompt string and the answer provided can be left empty. If the user does not enter anything (just presses return) then the variable will be unchanged and the errorlevel will be set to 1. The script above strips out any '&' and " characters but may still break if the string provided contains both. For user provided input, it is a good idea to fully sanitize any input string for potentially problematic characters (unicode/smart quotes etc). The CHOICE command is an alternative for user input, CHOICE accepts only one character/keypress, when selecting from a limited set of options it will be faster to use.

Echo a string with no trailing CR/LF

The standard ECHO command will always add a CR/LF to the end of each string displayed, returning the cursor to the start of the next line. SET /P does not do this, so it can be used to display a string. Feed a NUL character into SET /P like this, so it doesn’t wait for any user input: Set /P _scratch="This is a message to the user " <nul

Place the first line of a file into a variable:

Set /P _MyVar=<MyFilename.txt Echo %_MyVar% The second and any subsequent lines of text in the file will be discarded. In very early versions of CMD, any carriage returns/new lines (CR+LF) before the first line containing text were ignored.

Delete a variable

Type SET with just the variable name and an equals sign: SET _department= Better still, to be sure there is no trailing space after the = place the expression in parentheses or quotes: (SET _department=)   or SET "_department="

Arithmetic expressions (SET /a)

Placing expressions in "quotes" is optional for simple arithmetic but required for any expression using logical operators or parentheses. A best practice is to use quotes around all SET /A expressions, then they will always be in place when needed. When referring to a variable in your expression, SET /A allows you to omit the %’s so _myvar instead of %_myvar% The expression to be evaluated can include the following operators: For the Modulus operator use (%) on the command line, or in a batch script it must be doubled up to (%%) as below. This is to distinguish it from a FOR parameter. + Add set /a "_num=_num+5" += Add variable set /a "_num+=5" - Subtract set /a "_num=_num-5" -= Subtract variable set /a "_num-=5" * Multiply set /a "_num=_num*5" *= Multiply variable set /a "_num*=5" / Divide set /a "_num=_num/5" /= Divide variable set /a "_num/=5" %% Modulus set /a "_num=17%%5" %%= Modulus set /a "_num%%=5" ! Logical negation 0 (FALSE) ⇨ 1 (TRUE) and any non-zero value (TRUE) ⇨ 0 (FALSE) ~ Bitwise invert & AND set /a "_num=5&3" 0101 AND 0011 = 0001 (decimal 1) &= AND variable set /a "_num&=3" | OR set /a "_num=5|3" 0101 OR 0011 = 0111 (decimal 7) |= OR variable set /a "_num|=3" ^ XOR set /a "_num=5^3" 0101 XOR 0011 = 0110 (decimal 6) ^= XOR variable set /a "_num=^3" << Left Shift . (sign bit ⇨ 0) An arithmetic shift. >> Right Shift . (Fills in the sign bit such that a negative number always remains negative.) Neither ShiftRight nor ShiftLeft will detect overflow. <<= Left Shift variable set /a "_num<<=2" >>= Right Shift variable set /a "_num>>=2" ( ) Parenthesis group expressions set /a "_num=(2+3)*5" , Commas separate expressions set /a "_num=2,_result=_num*5" Any SET /A calculation that returns a fractional result will be rounded down to the nearest whole integer. Floating point arithmetic is not supported but you can call PowerShell for that: powershell.exe 12.9999999 + 2105001.01 or in a batch file: For /F %%G in ('powershell.exe 12.9999999 + 2105001.01') do Echo Result: %%G If a variable name is specified as part of the expression, but is not defined in the current environment, then SET /a will use a value of 0. SET /A arithmetic shift operators do not detect overflow which can cause problems for any non-trivial math, e.g. the bitwise invert often incorrectly reverses the + / - sign of the result. See SET /a examples below and this forum thread for more. also see SetX , VarSearch and VarSubstring for more on variable manipulation. SET /A should work within the full range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647) but in practice for negative integers it will not go below -2,147,483,647 because the correct two’s complement result 2,147,483,648 would cause a positive overflow. Examples SET /A "_result=2+4" (=6) SET /A "_result=5" (=5) SET /A "_result += 5" (=10) SET /A "_result=2 << 3" (=16) { 2 Lsh 3 = binary 10 Lsh 3 = binary 10000 = decimal 16 } SET /A "_result=5 %% 2" (=1) { 5/2 = 2 + 2 remainder 1 = 1 } SET /A "_var1=_var2=_var3=10" (sets 3 variables to the same value - undocumented syntax.) SET /A will treat any character string in the expression as an environment variable name. This allows you to do arithmetic with environment variables without having to type any % signs to get the values. SET /A "_result=5 + _MyVar " Multiple calculations can be performed in one line, by separating each calculation with commas, for example: Set "_year=1999" Set /a "_century=_year/100, _next=_century+1" The numbers must all be within the range of 32 bit signed integer numbers (-2,147,483,648 through 2,147,483,647) to handle larger numbers use PowerShell or VBScript . You can also store a math expression in a variable and substitute in different values, rather like a macro . SET "_math=(#+6)*5" SET /A _result="%_math:#=4% Echo %_result% SET /A _result="%_math:#=10% Echo %_result%

Leading Zero will specify Octal

Numeric values are decimal numbers, unless prefixed by 0x for hexadecimal numbers, 0 for octal numbers. So 0x10 = 020 = 16 decimal The octal notation can be confusing - all numeric values that start with zeros are treated as octal but 08 and 09 are not valid octal digits. For example SET /a "_month=07 " will return the value 7, but SET /a "_month=09" will return an error.

Permanent changes

Changes made using the SET command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed. To permanently change a variable at the command line use SetX or with the GUI: Control Panel ➞ System ➞ Environment ➞ System/User Variables Changing a variable permanently with SetX will not affect any CMD prompt that is already open. Only new CMD prompts will get the new setting. You can of course use SetX in conjunction with SET to change both at the same time: Set _Library=T:\Library\ SetX _Library T:\Library\ /m

Change the environment for other sessions

Neither SET nor SetX will affect other CMD sessions that are already running on the machine. This as a good thing, particularly on multi-user machines, your scripts won’t have to contend with a dynamically changing environment while they are running. It is possible to add permanent environment variables to the registry ( HKCU\Environment ), but this is an undocumented (and likely unsupported) technique and still it will not take effect until the users next login. System environment variables can be found in the registry here: HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
The CALL SET syntax will expand any variables passed on the same line, which is useful if you need to set one variable based on the value of another variable. CALL SET can also evaluate a variable substring , the CALL page has more detail on this technique, though in many cases a faster to execute solution is to use Setlocal EnableDelayedExpansion .

Autoexec.bat

Any SET statement in c:\autoexec.bat will be parsed at boot time Variables set in this way are not available to 32 bit gui programs - they won’t appear in the control panel. They will appear at the CMD prompt. If autoexec.bat CALLS any secondary batch files, the additional batch files will NOT be parsed at boot. This behaviour can be useful on a dual boot PC.

Errorlevels

When CMD Command Extensions are enabled (the default): Event Errorlevel If the variable was successfully changed. Errorlevel = unchanged , SET No variable found or invalid name. SET _var=value when _var name starts with "/" and not enclosed in quotes. SET /P Empty response from user. 1 SET /A Unbalanced parentheses 1073750988 SET /A Missing operand 1073750989 SET /A Syntax error 1073750990 SET /A Invalid number 1073750991 SET /A Number larger than 32-bits 1073750992 SET /A Division by zero 1073750993 If the Errorlevel is unchanged , typically it will be 0 but if a previous command set an errorlevel, that will be preserved (this is a bug).

# I got my mind set on you # I got my mind set on you... - Rudy Clark ( James Ray / George Harrison )

Related commands

Syntax - VarSubstring Extract part of a variable (substring). Syntax - VarSearch Search & replace part of a variable. Syntax - Environment Variables - List of default variables. CALL - Evaluate environment variables. CHOICE - Accept keyboard input to a batch file. ENDLOCAL - End localisation of environment changes, use to return values. EXIT - Set a specific ERRORLEVEL. PATH - Display or set a search path for executable files. REG - Read or Set Registry values. SETLOCAL - Begin localisation of environment variable changes. SETX - Set an environment variable permanently. Parameters - get a full or partial pathname from a command line variable. StackOverflow - Storing a Newline in a variable. Equivalent PowerShell: Set-Variable - Set a variable and a value (set/sv). Equivalent PowerShell: Read-Host - Prompt for user input. Equivalent bash command (Linux): env - Display, set, or remove environment variables.

/* steve jansen */

// another day in paradise hacking code and more, windows batch scripting: variables.

Mar 1 st , 2013 | Comments

  • Part 1 – Getting Started
  • Part 2 – Variables
  • Part 3 – Return Codes
  • Part 4 – stdin, stdout, stderr
  • Part 5 – If/Then Conditionals
  • Part 6 – Loops
  • Part 7 – Functions
  • Part 8 – Parsing Input
  • Part 9 – Logging
  • Part 10 – Advanced Tricks

Today we’ll cover variables, which are going to be necessary in any non-trivial batch programs. The syntax for variables can be a bit odd, so it will help to be able to understand a variable and how it’s being used.

Variable Declaration

DOS does not require declaration of variables. The value of undeclared/uninitialized variables is an empty string, or "" . Most people like this, as it reduces the amount of code to write. Personally, I’d like the option to require a variable is declared before it’s used, as this catches silly bugs like typos in variable names.

Variable Assignment

The SET command assigns a value to a variable.

NOTE: Do not use whitespace between the name and value; SET foo = bar will not work but SET foo=bar will work.

The /A switch supports arthimetic operations during assigments. This is a useful tool if you need to validated that user input is a numerical value.

A common convention is to use lowercase names for your script’s variables. System-wide variables, known as environmental variables, use uppercase names. These environmental describe where to find certain things in your system, such as %TEMP% which is path for temporary files. DOS is case insensitive, so this convention isn’t enforced but it’s a good idea to make your script’s easier to read and troubleshoot.

WARNING: SET will always overwrite (clobber) any existing variables. It’s a good idea to verify you aren’t overwriting a system-wide variable when writing a script. A quick ECHO %foo% will confirm that the variable foo isn’t an existing variable. For example, it might be tempting to name a variable “temp”, but, that would change the meaning of the widely used “%TEMP%” environmental varible. DOS includes some “dynamic” environmental variables that behave more like commands. These dynamic varibles include %DATE% , %RANDOM% , and %CD% . It would be a bad idea to overwrite these dynamic variables.

Reading the Value of a Variable

In most situations you can read the value of a variable by prefixing and postfixing the variable name with the % operator. The example below prints the current value of the variable foo to the console output.

There are some special situations in which variables do not use this % syntax. We’ll discuss these special cases later in this series.

Listing Existing Variables

The SET command with no arguments will list all variables for the current command prompt session. Most of these varaiables will be system-wide environmental variables, like %PATH% or %TEMP% .

NOTE: Calling SET will list all regular (static) variables for the current session. This listing excludes the dynamic environmental variables like %DATE% or %CD% . You can list these dynamic variables by viewing the end of the help text for SET, invoked by calling SET /?

Variable Scope (Global vs Local)

By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL , any variable assignments revert upon calling ENDLOCAL , calling EXIT , or when execution reaches the end of file (EOF) in your script.

Special Variables

There are a few special situations where variables work a bit differently. The arguments passed on the command line to your script are also variables, but, don’t use the %var% syntax. Rather, you read each argument using a single % with a digit 0-9, representing the ordinal position of the argument. You’ll see this same style used later with a hack to create functions/subroutines in batch scripts.

There is also a variable syntax using ! , like !var! . This is a special type of situation called delayed expansion. You’ll learn more about delayed expansion in when we discuss conditionals (if/then) and looping.

Command Line Arguments to Your Script

You can read the command line arguments passed to your script using a special syntax. The syntax is a single % character followed by the ordinal position of the argument from 0 – 9 . The zero ordinal argument is the name of the batch file itself. So the variable %0 in our script HelloWorld.cmd will be “HelloWorld.cmd”.

The command line argument variables are * %0 : the name of the script/program as called on the command line; always a non-empty value * %1 : the first command line argument; empty if no arguments were provided * %2 : the second command line argument; empty if a second argument wasn’t provided * …: * %9 : the ninth command line argument

NOTE: DOS does support more than 9 command line arguments, however, you cannot directly read the 10th argument of higher. This is because the special variable syntax doesn’t recognize %10 or higher. In fact, the shell reads %10 as postfix the %0 command line argument with the string “0”. Use the SHIFT command to pop the first argument from the list of arguments, which “shifts” all arguments one place to the left. For example, the the second argument shifts from position %2 to %1 , which then exposes the 10th argument as %9 . You will learn how to process a large number of arguments in a loop later in this series.

Tricks with Command Line Arguments

Command Line Arguments also support some really useful optional syntax to run quasi-macros on command line arguments that are file paths. These macros are called variable substitution support and can resolve the path, timestamp, or size of file that is a command line argument. The documentation for this super useful feature is a bit hard to find – run ‘FOR /?’ and page to the end of the output.

  • %~I removes quotes from the first command line argument, which is super useful when working with arguments to file paths. You will need to quote any file paths, but, quoting a file path twice will cause a file not found error.

SET myvar=%~I

%~fI is the full path to the folder of the first command line argument

%~fsI is the same as above but the extra s option yields the DOS 8.3 short name path to the first command line argument (e.g., C:\PROGRA~1 is usually the 8.3 short name variant of C:\Program Files ). This can be helpful when using third party scripts or programs that don’t handle spaces in file paths.

%~dpI is the full path to the parent folder of the first command line argument. I use this trick in nearly every batch file I write to determine where the script file itself lives. The syntax SET parent=%~dp0 will put the path of the folder for the script file in the variable %parent% .

%~nxI is just the file name and file extension of the first command line argument. I also use this trick frequently to determine the name of the script at runtime. If I need to print messages to the user, I like to prefix the message with the script’s name, like ECHO %~n0: some message instead of ECHO some message . The prefixing helps the end user by knowing the output is from the script and not another program being called by the script. It may sound silly until you spend hours trying to track down an obtuse error message generated by a script. This is a nice piece of polish I picked up from the Unix/Linux world.

Some Final Polish

I always include these commands at the top of my batch scripts:

The SETLOCAL command ensures that I don’t clobber any existing variables after my script exits. The ENABLEEXTENSIONS argument turns on a very helpful feature called command processor extensions. Trust me, you want command processor extensions. I also store the name of the script (without the file extension) in a variable named %me% ; I use this variable as the prefix to any printed messages (e.g. ECHO %me%: some message ). I also store the parent path to the script in a variable named %parent% . I use this variable to make fully qualified filepaths to any other files in the same directory as our script.

<< Part 1 – Getting Started Part 3 – Return Codes >>

Site navigation

  • Assoc and Ftype
  • Batch files- basics
  • Batch files - branching
  • Batch files- iterating
  • Command Line- Introduction
  • Command line list and reference
  • Commands that everybody can use
  • Configuring the command prompt window
  • Disk management-Diskpart
  • File system utility- Fsutil
  • Net Services
  • Network Services Shell
  • Recovery Console
  • Recovery Console- Commands
  • Registry editor console
  • Scripts in the command line
  • Server 2003 tools for XP
  • Service Controller Command (SC)
  • Shell command
  • Start-Run line
  • Support tools
  • TCP/IP networking tools
  • Tips for using the command shell
  • Tskill and Taskkill
  • Variables and "Set"
  • Vista command list
  • Vista/7 command line tips
  • Windows 7 command list

Related links

  • Computer Education
  • Blog with tips
  • Windows for Beginners

How variables are defined with the "set" command

In one sense, there are two categories of variables for the command line. Some might use the term "variable" for the placeholders or arguments %1, %2, ..%9 , that are used to represent user input in batch files. ( See the discussion on this page .) However, the term "variable" is normally reserved in command line usage for entities that are declared as environment variables with the "set" command. Note that this is a pretty primitive way to define variables. For example, there is no typing. Environment variables, including numbers, are stored as strings and operations with them have to take that into account. Variables are declared and given a value in a single statement using "set". .The syntax is: set some_variable = some_value Variable names are not case-sensitve and can consist of the usual alphanumeric and other common characters. Some characters are reserved and have to be escaped. They should be avoided. These include the symbols in Table II on this page . Also, since these are environment variables, their names should be enclosed in percent signs when used in references and expressions, e.g , %some_variable% . The percent signs are not used in the left side of the set statement that declares a variable.

Localizing variables

The declaration of a variable lasts as long as the present command window is open. If you are using a batch file that does not close its instance of the command window when the batch file terminates, any variables that the batch file declares remain. If you wish to localize a variable to a particular set of statements, use the "setlocal" and "endlocal" commands. Thus. to confine a variable declaration to a particular block of code, use: .... setlocal set some_variable = some_value ... some statements endlocal ...

Variables from user input

The "set" command can also accept input from a user as the value for a variable. The switch " /p " is used for this purpose. A batch file will wait for the user to enter a value after the statement set /p new_variable= When the user has entered the value, the script will continue. A message string to prompt for input can also be used. For example: set /p new_variable="Enter value " Note the space at the end of the prompt message. Otherwise, the prompt message and the user-entered value will run together on the screen. It works but it looks funny. The user may be tempted to hit the spacebar, which adds a leading space to the input value.

Arithmetic operations

The command line is not designed for handling mathematical functions but it is possible to do some very simple integer arithmetic with variables. A switch " /a " was added to the "set" command to allow for some basic functions. Primarily, the use is adding and subtracting. For example, it is possible to increment or decrement counters in a loop. In principle, it is also possible to do multiplication and division.but only whole numbers can be handled so the practical use is limited. Although variables are stored as strings, the command interpreter recognizes strings that contain only integers, allowing them to be used in arithmetic expressions. The syntax is set /a some_variable= {arithmetic expression} The four arithmetic operators are shown in Table I. (I have omitted a "modulus" operation, which uses the % sign in yet another way. In my opinion this just adds difficulty to an already quirky syntax. Using % in more than one sense can only confuse.)

Here is an example of a variable %counter% being incremented: set /a counter=%counter%+1 This can also be written as: set /a counter+=1

Variables in comparison statements in batch files

Variables are often used in comparisons in conditional statements in batch files. Some of the comparison operators that are used are given in Table I of the page on "If" statements . Because of the somewhat loose way that the command line treats variables, it is necessary to be careful when comparing variables. For strings, the safest way is to quote variables. For example: if "%variable1%" == "%variable2%" some_command

Back to top

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

set (environment variable)

  • 9 contributors

Displays, sets, or removes cmd.exe environment variables. If used without parameters, set displays the current environment variable settings.

This command requires command extensions, which are enabled by default.

The set command can also run from the Windows Recovery Console, using different parameters. For more information, see Windows Recovery Environment (WinRE) .

If command extensions are enabled (the default) and you run set with a value, it displays all of the variables that begin with that value.

The characters < , > , | , & , and ^ are special command shell characters, and they must be preceded by the escape character ( ^ ) or enclosed in quotation marks when used in <string> (for example, "StringContaining&Symbol"). If you use quotation marks to enclose a string that contains one of the special characters, the quotation marks are set as part of the environment variable value.

Use environment variables to control the behavior of some batch files and programs and to control the way Windows and the MS-DOS subsystem appears and works. The set command is often used in the Autoexec.nt file to set environment variables.

If you use the set command without any parameters, the current environment settings are displayed. These settings usually include the COMSPEC and PATH environment variables, which are used to help find programs on disk. Two other environment variables used by Windows are PROMPT and DIRCMD .

If you specify values for <variable> and <string> , the specified <variable> value is added to the environment and <string> is associated with that variable. If the variable already exists in the environment, the new string value replaces the old string value.

If you specify only a variable and an equal sign (without <string> ) for the set command, the <string> value associated with the variable is cleared (as if the variable isn't there).

If you use the /a parameter, the following operators are supported, in descending order of precedence:

If you use logical ( && or || ) or modulus ( % ) operators, enclose the expression string in quotation marks. Any non-numeric strings in the expression are considered environment variable names, and their values are converted to numbers before they're processed. If you specify an environment variable name that isn't defined in the current environment, a value of zero is allotted, which allows you to perform arithmetic with environment variable values without using the % to retrieve a value.

If you run set /a from the command line outside of a command script, it displays the final value of the expression.

Numeric values are decimal numbers unless prefixed by 0× for hexadecimal numbers or 0 for octal numbers. Therefore, 0×12 is the same as 18, which is the same as 022.

Delayed environment variable expansion support is disabled by default, but you can enable or disable it by using cmd /v .

When creating batch files, you can use set to create variables, and then use them in the same way that you would use the numbered variables %0 through %9 . You can also use the variables %0 through %9 as input for set .

If you call a variable value from a batch file, enclose the value with percent signs ( % ). For example, if your batch program creates an environment variable named BAUD , you can use the string associated with BAUD as a replaceable parameter by typing %baud% at the command prompt.

To set the value TEST^1 for the environment variable named testVar , type:

The set command assigns everything that follows the equal sign (=) to the value of the variable. Therefore, if you type set testVar=TEST^1 , you'll get the following result, testVar=TEST1 .

To set the value TEST&1 for the environment variable testVar , type:

To set an environment variable named include so the string c:\directory is associated with it, type:

You can then use the string c:\directory in batch files by enclosing the name include with percent signs ( % ). For example, you can use dir %include% in a batch file to display the contents of the directory associated with the include environment variable. After this command is processed, the string c:\directory replaces %include% .

To use the set command in a batch program to add a new directory to the path environment variable, type:

To display a list of all of the environment variables that begin with the letter p , type:

To display a list of all of the environment variables on the current device, type:

Related links

  • Command-Line Syntax Key

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Creating Variables

Do you find yourself repeating the same string multiple times when working with batch files?

For example, when copying a specific file and then moving it to a copied folder, you end up writing the same path multiple times like this:

When copying and moving, C:\Users\user\Documents\sample.txt is written twice.

Although this is not a problem, writing the same string multiple times can cause typing errors and make corrections difficult.

To solve this problem, variables can be defined in batch files .

By defining variables, there is no need to write the same string multiple times, reducing the risk of typing errors.

Rewriting the previous example using variables would look like this:

The variable source is assigned to the string C:\Users\user\Documents\sample.txt , which was previously written twice.

By doing this, simply writing %source% will have the same meaning as C:\Users\user\Documents\sample.txt .

This page introduces how to define variables in batch files and provides specific examples of using variables.

How to Define Variables

To define variables, use the set command.

After the set command, specify the variable name and value.

Do not put spaces before or after the equals sign.

Options for the set Command

In addition to defining variables in advance as mentioned above, the set command can also accept user input when executed as a batch file, depending on the specified options.

By specifying the /P option, you can accept input from the user.

The above command does not mean that the string “display_message” is assigned to a variable named “variable_name”.

By specifying the /P option, the set command accepts input from the user.

The “display_message” part is the message displayed on the screen when accepting a value to store in a variable.

When the above batch file is actually executed, it will be displayed as follows:

Command Prompt Icon

The batch file waits until it receives input from the user, and no processing is performed after the set command.

When the user enters a value and presses Enter, the entered value is assigned to the variable, and processing after the set command is executed.

Specific Examples Using Variables

Concatenating strings, variables and strings.

To concatenate variables and specific strings, no operator is required, and write %variable_name%string .

Variables and Variables

For concatenating variables and variables, write %variable_name1%%variable_name2% .

Calculating Mathematical Expressions

You can perform mathematical calculations using the set /A command to store the results of the calculation in a variable.

When you run the above batch file, it will be displayed as follows:

Using Environment Variables

In batch files, you can use predefined environment variables in addition to variables that you define yourself.

Environment variables are variables provided by Windows that store information about Windows.

List of Environment Variables

%userprofile% and others are commonly used, so it is useful to remember them.

Examples of using environment variables

Creating a file in the user’s home folder, confirmation test.

What option do you need to specify to accept user input as a variable?

Windows: Set Environment Variable – CMD & PowerShell

What is an environment variable in Windows? An environment variable is a dynamic “object” containing an editable value which may be used by one or more software programs in Windows.

In this note i am showing how to set an environment variable in Windows from the command-line prompt (CMD) and from the Windows PowerShell.

In the examples below i will set an environment variable temporary (for the current terminal session only), permanently for the current user and globally for the whole system.

Cool Tip: Add a directory to Windows %PATH% environment variable! Read More →

Set Environment Variable For The Current Session

Set an environment variable for the current terminal session:

Print an environment variable to the console:

Cool Tip: List Windows environment variables and their values! Read More →

Set Environment Variable Permanently

Run as Administrator: The setx command is only available starting from Windows 7 and requires elevated command prompt. It works both for the Windows command-line prompt (CMD) and the Windows PowerShell.

Permanently set an environment variable for the current user:

Permanently set global environment variable (for all users):

Info: To see the changes after running setx – open a new command prompt.

3 Replies to “Windows: Set Environment Variable – CMD & PowerShell”

' src=

Thanks for your help !

' src=

AWESOME! Thanks 🙂

' src=

Thanks so much!

Leave a Reply Cancel reply

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Store output of Windows command in batch file

I need to store the output of a command line in a variable. How can I do this?

  • command-line-interface

Ben Pilbrow's user avatar

  • Duplicate if How do I get the result of a command in a variable in windows? from Stack Overflow. –  Cristian Ciupitu Jul 1, 2014 at 16:56

3 Answers 3

Provided a simple batch file test.cmd with the contents:

You can set the output into a variable with the following command line:

Used on the command line like this:

Should you want to use the FOR within a batch file, rather than command line, you need to change %a to %%a .

jscott's user avatar

  • Your prompt doesn't have > for some reason which makes reading the commands more difficult since "C:\SET", for example, starts out looking like a path. –  Dennis Williamson Mar 10, 2011 at 15:22
  • @Dennis Edited. Sorry about that, should have used copy/paste. –  jscott Mar 10, 2011 at 15:42

This is how I do this:

If result.txt has more than 1 line, only the top line of the file is used for %DATA%. You could also make result.txt into a variable itself, such as %OUTPUT%.

jftuga's user avatar

You can pipe the command into something like:

What you see above sends the output to a named file. If file does not exist, it creates one. Overwrites existing file And you can also do this:

This appends the output to contents of a named file or creates a file if none exists

See also here: Using command redirection operators

Turdie's user avatar

  • 6 Would you please expand your answer to explain how this stores anything in a variable? –  jscott Mar 10, 2011 at 13:48
  • i want to store output in variable .... and i try this method but it is failed ansd the output of command : commandline 1>fiel.txt what is "1" mean ??? and the file didn't creat –  Mohammad AL-Rawabdeh Mar 10, 2011 at 13:50

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged windows command-line-interface batch-file ..

  • The Overflow Blog
  • OverflowAI and the holy grail of search
  • The Good, the Bad, and the Disruptive: Let us know where you stand in the...
  • Featured on Meta
  • Our Partnership with OpenAI
  • What deliverables would you like to see out of a working group?

Hot Network Questions

  • Why would academics spend funds on an apparently unnecessary publishing fee?
  • fmap for containers in c++
  • Identify the sequence of -3, -1, 3, 11, 27, ...
  • NTSC scan lines used by 8-bit computers
  • Cubic splines in Cox model
  • How to know if you've caught a pokemon in the catching screen in Pokemon Go
  • Assistance with an exercise on field endomorphisms
  • Movie where the only survivor from a space colony or expedition is found and recovered by a ship. He turns out to be infected and turns evil
  • Is the action of the Laplacian on the Schur polynomials known?
  • Does Dragonskin Armor Affect Ranger's Dual Wield?
  • Advice on making a quad-directional power/data connector
  • Why has the Cuban government invested little or nothing on biofuels?
  • Can I say "Rolex watches are astronomical", "astronomical" in the sense of "expensive"?
  • API Generator for Python
  • Can this 1930s box support a ceiling fan?
  • I got something for you
  • Why "guilty" or "not guilty"and not "guilty" or "innocent"?
  • Is it a problem to have a washing machine plugged into a GFCI outlet?
  • Is 1 Kings 18 talking about the daily evening sacrifice?
  • Are there any dangerous consequences when allowing spending inspiration on rerolls?
  • In what situation would universal full-body protective clothing be preferable to living in sealed habitats?
  • What was this old fantasy book based on the lost meditation of Rene Descartes?
  • What happens to the ring singularities when two Kerr black holes merge?
  • Are circles required on the edge of the grid?

assign variable cmd

Batch Script Tutorial

  • Batch Script Tutorial
  • Batch Script - Home
  • Batch Script - Overview
  • Batch Script - Environment
  • Batch Script - Commands
  • Batch Script - Files
  • Batch Script - Syntax

Batch Script - Variables

  • Batch Script - Comments
  • Batch Script - Strings
  • Batch Script - Arrays
  • Batch Script - Decision Making
  • Batch Script - Operators
  • Batch Script - DATE & TIME
  • Batch Script - Input / Output
  • Batch Script - Return Code
  • Batch Script - Functions
  • Batch Script - Process
  • Batch Script - Aliases
  • Batch Script - Devices
  • Batch Script - Registry
  • Batch Script - Network
  • Batch Script - Printing
  • Batch Script - Debugging
  • Batch Script - Logging
  • Batch Script Resources
  • Batch Script - Quick Guide
  • Batch Script - Useful Resources
  • Batch Script - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

There are two types of variables in batch files. One is for parameters which can be passed when the batch file is called and the other is done via the set command.

Command Line Arguments

Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on.

The following example shows a batch file which accepts 3 command line arguments and echo’s them to the command line screen.

If the above batch script is stored in a file called test.bat and we were to run the batch as

Following is a screenshot of how this would look in the command prompt when the batch file is executed.

Command Line Arguments

The above command produces the following output.

If we were to run the batch as

The output would still remain the same as above. However, the fourth parameter would be ignored.

Set Command

The other way in which variables can be initialized is via the ‘set’ command. Following is the syntax of the set command.

variable-name is the name of the variable you want to set.

value is the value which needs to be set against the variable.

/A – This switch is used if the value needs to be numeric in nature.

The following example shows a simple way the set command can be used.

In the above code snippet, a variable called message is defined and set with the value of "Hello World".

To display the value of the variable, note that the variable needs to be enclosed in the % sign.

Working with Numeric Values

In batch script, it is also possible to define a variable to hold a numeric value. This can be done by using the /A switch.

The following code shows a simple way in which numeric values can be set with the /A switch.

We are first setting the value of 2 variables, a and b to 5 and 10 respectively.

We are adding those values and storing in the variable c.

Finally, we are displaying the value of the variable c.

The output of the above program would be 15.

All of the arithmetic operators work in batch files. The following example shows arithmetic operators can be used in batch files.

Local vs Global Variables

In any programming language, there is an option to mark variables as having some sort of scope, i.e. the section of code on which they can be accessed. Normally, variable having a global scope can be accessed anywhere from a program whereas local scoped variables have a defined boundary in which they can be accessed.

DOS scripting also has a definition for locally and globally scoped variables. By default, variables are global to your entire command prompt session. Call the SETLOCAL command to make variables local to the scope of your script. After calling SETLOCAL, any variable assignments revert upon calling ENDLOCAL, calling EXIT, or when execution reaches the end of file (EOF) in your script. The following example shows the difference when local and global variables are set in the script.

Few key things to note about the above program.

The ‘globalvar’ is defined with a global scope and is available throughout the entire script.

The ‘var‘ variable is defined in a local scope because it is enclosed between a ‘SETLOCAL’ and ‘ENDLOCAL’ block. Hence, this variable will be destroyed as soon the ‘ENDLOCAL’ statement is executed.

You will notice that the command echo %var% will not yield anything because after the ENDLOCAL statement, the ‘var’ variable will no longer exist.

Working with Environment Variables

If you have variables that would be used across batch files, then it is always preferable to use environment variables. Once the environment variable is defined, it can be accessed via the % sign. The following example shows how to see the JAVA_HOME defined on a system. The JAVA_HOME variable is a key component that is normally used by a wide variety of applications.

The output would show the JAVA_HOME directory which would depend from system to system. Following is an example of an output.

To Continue Learning Please Login

Security, software development and devops in a cloud world

  • Article Content
  • Presentations
  • Certifications
  • Stackoverflow
  • Buy me a coffee

Windows Command Prompt – Loading a File into a Variable

By John Hanley on October 26th, 2018 in Programming

Often I need to load the content of a file into a Windows Command Prompt variable. This is useful when writing batch scripts where the return value from one program is used as input for another program. At other times I need to process a json file to load just a value into a variable.

Note: There is a limit to the size of variables. I think the limit is 1024 bytes.

Let’s start with a sample test file “testfile”:

And another sample test file “testfile.json”:, load the first line from testfile into a variable:.

This outputs:

Load the last line from testfile into a variable:

Load all lines from testfile.json into a variable:, load just a value from a json file:, load just a value from a json file without the quotes:.

John Hanley

I design software for enterprise-class systems and data centers. My background is 30+ years in storage (SCSI, FC, iSCSI, disk arrays, imaging) virtualization. 20+ years in identity, security, and forensics.

For the past 14+ years, I have been working in the cloud (AWS, Azure, Google, Alibaba, IBM, Oracle) designing hybrid and multi-cloud software solutions. I am an MVP/GDE with several.

Related Posts

  • What programming language do I write software in?
  • Understanding Google Cloud Storage Scopes
  • Socratica Python Kickstarter Project
  • Google Cloud Stackdriver – IP Addresses
  • Google Cloud IAM – Listing Projects

John Hanley

October 26, 2018

Programming

Batch Files , json , Windows Command Prompt

Leave a Reply Cancel reply

Subscribe to blog via email.

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Email Address

Terraform and Cost Controls

Repeatable gcp environments.

  • Certification (8)
  • Deno Deploy (1)
  • DevOps (13)
  • G Suite (3)
  • Google (73)
  • HashiCorp (1)
  • Hostwinds (1)
  • Kubernetes (2)
  • Laravel (4)
  • MongoDB (2)
  • OpenShift (3)
  • OpenSSH (1)
  • Paramiko (1)
  • Programming (11)
  • Pyodide (16)
  • Pyscript (18)
  • Python (16)
  • Red Hat (2)
  • Security (13)
  • SSH Tunnels (1)
  • Terraform (3)
  • WebAssembly (1)
  • WireGuard (1)
  • WordPress (2)

Recent Posts

  • Google Cloud Run – Rust Hello World – Part 2
  • Google Cloud Run – Rust Hello World – Part 1
  • Google Certification – Cloud Bigtable
  • Google Professional Cloud Architect Certification
  • Google Cloud – C++ Software Development
  • Google Cloud Environment Variables
  • WordPress – Solving Common Problems
  • SSH: Signature Algorithm ssh-rsa Error
  • Bunny.net: Account and API Keys
  • DNS: Solving Google Managed SSL Certificate Issue Problems
  • PyScript – MongoDB Data API
  • MongoDB: Trivia
  • PyScript: Deno Deploy
  • PyScript: Apache Web Server Setup
  • PyScript: Interfacing with WASM
  • PyScript: Debugging and Error Management Strategies
  • PyScript: Creating Installable Offline Applications
  • PyScript – Getting Application Data
  • PyScript: Third Party Criticism of PyScript
  • Pyscript: Files and File Systems – Part 2
  • Pyscript: Building from Source
  • PyScript: Good Videos to Watch
  • Pyscript: Files and File Systems – Part 1
  • Pyscript: Graphics
  • PyScript: Create the py-script tag at Runtime
  • Pyscript: JavaScript Event Callbacks
  • Pyscript: Page Load Time
  • PyScript: JavaScript and Python Interoperability
  • PyScript: Loading Python Code in the Browser
  • Impact of Russia/Ukraine on Cloud Developers
  • GitHub – Create a Self-Hosted Runner – Part 2
  • GitHub – Create a Self-Hosted Runner – Hyper-V plus Ubuntu
  • January 2022 – Git and GitHub
  • PHP 8: Setup PHP_SSH2
  • Ubuntu 20.04 Desktop – Installing and Configuring SSH
  • Laravel – Adding Azure Blob Storage
  • Azure – OpenID Connect JSON Web Key Set
  • Azure – Setting up a Development Environment for Python
  • Laravel – GitHub Integration – Part 1
  • Azure – Update Network Security Group Rule with my IP Address
  • Azure – Lock a VM to Prevent Deletion
  • Azure – Recovering from UFW firewall lockout – Ubuntu
  • Deep Dive into Google Cloud IAM Signblob and Service Accounts
  • Google Cloud Application Default Credentials – PHP
  • What is Amezmo?
  • Laravel – Redirecting HTTP to HTTPS
  • Laravel – Displaying a GitHub Gist
  • WireGuard Introduction
  • Terraform – Experiments with Google Cloud DNS and IAM
  • Google Professional Cloud Security Engineer Recertification
  • Oct 23 - IBM Cloud & OpenShift Podcast
  • Oct 22 - New Google Cloud Billing Video
  • Oct 10 - New Get Cooking in Cloud Video
  • Oct 9 - New Cloud Storage Bytes Video
  • Sep 4 – Google Cloud Podcast

Address [email protected] Seattle, WA 98118

Hours Normally 9 AM to 5 PM, but I often work very long hours on projects.

© 2024 John Hanley — Powered by WordPress

Theme by Anders Noren — Up ↑

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get output of a CMD command and set it to a batch variable

I run this command to get name of groups:

but when I do this echo "%rdpgroup%" the output is like this:

I dont want those spaces at the end of users. Just want an output like this: "Remote Desktop Users"

  • command-line

Aria Fathi's user avatar

  • I've had a similar bug in the past, can't remember exactly, but I think it was resolved by removing random spaces in my script. For some reason cmd was adding unnecessary spaces because I have spaces elsewhere in my script. Try removing all spaces that aren't absolutely needed. I know it sounds random, but it worked in my case. –  IronWilliamCash Feb 26, 2018 at 18:44
  • @IronWilliamCash exactly what I need to remove those spaces. I don't know how. –  Aria Fathi Feb 26, 2018 at 19:30
  • You can remove undesirable whitespace with this form of command, just add it to the appropriate part of the script: set "rdpgroup=!rdpgroup: = !" (it simply converts two spaces to a single space, but you can change it to for example convert 4 spaces to a single space, or to convert 3 spaces to no spaces -- there are many possibilities). –  Ed999 Mar 26, 2019 at 6:56

2 Answers 2

The output of WMIC is unicode !

The trailing <CR> can be removed by passing the value through another FOR /F loop. This also removes the phantom "blank" line (actually a <CR> )

Hackoo's user avatar

Different ways to get the same results By ThunderJun:

OP1: Here we use setlocal to activate the use of special variables of the delayed type (!var!) Without using a for within another for. To get the same result.

OP2: Here we assign the command in a common type variable and with the help of vertical bar, we combine several commands, always taking priority first. We add the filter: more +1 to indicate to ignore the first output line and then add the filter: findstr /i "remot" with another vertical bar, with this we are indicating, that only print lines that contain the keyword that is in quotes and that does not distinguish between upper or lower case letters. Then we use a type variable common indicating to it, not to show the last 3 characters: %var:~0,-3% In this way, we get the same result without using a for within another for.

OP3: Here we use setlocal, to activate the use of special variables of delayed type (!var!). With a vertical bar, at the end of the command inside the for. For it, we assign a filter with the command: findstr /i "remot" indicating that it only prints lines with the keyword in quotes and that does not distinguish between upper and lower case letters. We use a special variable of delayed type, to capture the command output and we indicate replace 2 characters of spaces for nothing (!var: =!), to achieve the same result without using a for inside from another to.

FvUshyonFly's user avatar

  • If you are simply quoting Hackoo’s answer , please don’t do that. If you are presenting an improved version, please point out what you changed. –  Scott - Слава Україні Aug 4, 2019 at 7:52

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged windows command-line batch batch-file ..

  • The Overflow Blog
  • The Good, the Bad, and the Disruptive: Let us know where you stand in the...
  • How to train your dream machine
  • Featured on Meta
  • Our Partnership with OpenAI
  • What deliverables would you like to see out of a working group?

Hot Network Questions

  • Is 1 Kings 18 talking about the daily evening sacrifice?
  • API Generator for Python
  • My other Mac mini's clipboard history has my laptop's clipboard history and it's freaking me out
  • Cubic splines in Cox model
  • Why "guilty" or "not guilty"and not "guilty" or "innocent"?
  • What are the minimum system requirements to run GW-BASIC?
  • How can I create a matrix with a vector of 1 in the diagonal?
  • Strange C# behavior of a property with a nullable type
  • Tikz node position along edge, expressed in absolute distance
  • Appealing an Australian Visa Refusal (Tourist)
  • Does FIDE allow viewing how many IM/GM norms a player has?
  • NTSC scan lines used by 8-bit computers
  • Integral's computation does not match WolframAlpha result
  • Do particle & anti-particle pairs belong to the same field?
  • 1 Corinthians 15:4-7 a physical, or spiritual heavenly appearance
  • Comparing coefficients and confidence intervals when some categories have very few observations (logistic regression)
  • Retrosynthesis of 4-ethyl-2,2,5,5-tetramethyl-1,3-dioxane
  • I am trying to create a superior triangular table
  • Image recognition in air to air missiles
  • Freewheel removal
  • Can we install and run Ubuntu WSL for ARM on x86_64 windows machine?
  • Does Dragonskin Armor Affect Ranger's Dual Wield?
  • The older, the smarter. Is the wisdom of time a scientifically proven fact or just human prejudices?
  • Stealth In Space Calculator

assign variable cmd

IMAGES

  1. How To Set Environment Variable In Windows 11 Using Cmd

    assign variable cmd

  2. How To Set Environment Variables In Windows 10 Helpful Guide Solved

    assign variable cmd

  3. C# Tutorial Variables

    assign variable cmd

  4. How to Assign a Function to a Variable in Python?

    assign variable cmd

  5. How to assign permanent letters to drives on Windows 10

    assign variable cmd

  6. Windows Environment Variables

    assign variable cmd

VIDEO

  1. Can we Assign 128 to a variable of byte type? #coding #java #javaprogramming

  2. Введение работы с командной строкой CMD в WINDOWS. УРОК №1

  3. How to recode variables in R

  4. how to define a variable and assign value to variable in PHP, declare variable in PHP and value

  5. 15.1 Assign or Remove File Attribute in CMD

  6. PowerShell Variables

COMMENTS

  1. cmd

    6. Consider also using SETX - it will set variable on user or machine (available for all users) level though the variable will be usable with the next opening of the cmd.exe ,so often it can be used together with SET : ::setting variable for the current user. if not defined My_Var (. set "My_Var=My_Value".

  2. How to Use Windows CMD Environment Variables

    First, you need to launch Command Prompt, or CMD, as an administrator. Click Start, type "cmd" into the search box, and then click "Run as Administrator." Any user environment variable can be set or modified in a regular Command Prompt window, but changing system-wide environment variables requires an elevated Command Prompt. There are two ...

  3. Set

    SET. Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session. Syntax SET variable SET variable=string SET "variable=string" SET "variable=" SET /A "variable=expression" SET /P variable=[promptString] SET " Key variable A new or existing environment variable name e.g. _num string A text string to assign to the variable.

  4. Windows Batch Scripting: Variables

    You can read the command line arguments passed to your script using a special syntax. The syntax is a single % character followed by the ordinal position of the argument from 0 - 9. The zero ordinal argument is the name of the batch file itself. So the variable %0 in our script HelloWorld.cmd will be "HelloWorld.cmd".

  5. The Set command and how to use variables in the Windows command line

    Variables from user input. The "set" command can also accept input from a user as the value for a variable. The switch " /p " is used for this purpose. A batch file will wait for the user to enter a value after the statement set /p new_variable= When the user has entered the value, the script will continue. A message string to prompt for input ...

  6. set

    The set command assigns everything that follows the equal sign (=) to the value of the variable. Therefore, if you type set testVar=TEST^1, you'll get the following result, testVar=TEST1. You can then use the string c:\directory in batch files by enclosing the name include with percent signs ( % ).

  7. How do you set and call a path variable in command prompt?

    In Command Prompt (cmd.exe), you can set environment variables using set: set var=value set "var=value" ... If you change a variable in cmd or bash, it will not update the environment of all other running processes, or those you start from Explorer, or those you start from Start menu.

  8. How to Define and Use Variables in Batch Files with the set Command

    To define variables, use the set command. set variable_name = value. After the set command, specify the variable name and value. Do not put spaces before or after the equals sign. Options for the set Command. In addition to defining variables in advance as mentioned above, the set command can also accept user input when executed as a batch file ...

  9. Setting and using variable within same command line in Windows cmd.exe

    The only difference is that, because of the way cmd parses, the environment assignments need to be quoted, so your command would be: env "EDITOR=vim" command [up to 8 parameters] The batch file could be elaborated to remove the 8-parameter restriction by building up the command string within the for loop (delayed expansion will be needed).

  10. Windows: Set Environment Variable

    It works both for the Windows command-line prompt (CMD) and the Windows PowerShell. Permanently set an environment variable for the current user: C:\> setx VAR_NAME "VALUE". Permanently set global environment variable (for all users): C:\> setx /M VAR_NAME "VALUE". Info: To see the changes after running setx - open a new command prompt.

  11. CMD set variable to be result of a command

    for /f - Loop command against the results of another command. set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session. wmic - Windows Management Instrumentation Command. Share. Improve this answer. Follow. answered Oct 1, 2015 at 16:09.

  12. windows

    The variable is being Set inside a parenthesised code block, you probably need to enable delayed expansion. ... How set a variable and then use it in the same line in command prompt. 2. Set Variable to value of command. 0. Set a value in batch file variable from a CMD command. 0.

  13. Store output of Windows command in batch file

    Provided a simple batch file test.cmd with the contents: echo jscott. You can set the output into a variable with the following command line: FOR /F "tokens=*" %a in ('test.cmd') do SET OUTPUT=%a. Used on the command line like this: C:\>SET OUTPUT. Environment variable OUTPUT not defined. C:\>FOR /F "tokens=*" %a in ('test.cmd') do SET OUTPUT=%a.

  14. Assigning directory name to a variable in cmd batch

    An A-Z Index of the Windows CMD command line - An excellent reference for all ; cmd - Start a new CMD shell and (optionally) run a command/executable program. dir - Display a list of files and subfolders. set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.

  15. Windows echo command can't echo a user-set variable

    1. Note that the reason set tt works to display the value of the variable is that set var displays all variables beginning with var. You may notice the space between tt and = in the system output. Also, the value of the variable includes the initial space. For example echo last%tt % would output last name, which could be what is desired.

  16. Batch Script

    Batch scripts support the concept of command line arguments wherein arguments can be passed to the batch file when invoked. The arguments can be called from the batch files through the variables %1, %2, %3, and so on. The following example shows a batch file which accepts 3 command line arguments and echo's them to the command line screen.

  17. How can I assign the output of a command to a shell variable?

    A shell assignment is a single word, with no space after the equal sign. So what you wrote assigns an empty value to thefile; furthermore, since the assignment is grouped with a command, it makes thefile an environment variable and the assignment is local to that particular command, i.e. only the call to ls sees the assigned value.. You want to capture the output of a command, so you need to ...

  18. How to get a registry value and set into a variable in batch

    I need to get a value in a registry key and store in a variable using a batch file. I wrote a basic command line to exemplify my logic (using echo instead of setting a variable): for /f "tokens=3 delims= " %%a in ('reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v "LastUsedUsername" ^|findstr /ri "REG_SZ"') do echo=%%a ...

  19. Windows Command Prompt

    Often I need to load the content of a file into a Windows Command Prompt variable. This is useful when writing batch scripts where the return value from one program is used as input for another program. At other times I need to process a json file to load just a value into a variable. Note: There is a limit to the size of variables.

  20. How to assign command value to variable in batch

    I want to execute one command and assign it's value to a variable within a batch file. We know that running hostname command on a windows command prompt gives the PC name. I want to use hostname command and assign it's value to a variable within a batch file. After googling about it, I've tried using below methods, none of these seem to work:

  21. Get output of a CMD command and set it to a batch variable

    OP1: Here we use setlocal to activate the use of special variables of the delayed type (!var!) Without using a for within another for. To get the same result. OP2: Here we assign the command in a common type variable and with the help of vertical bar, we combine several commands, always taking priority first.