- Compress SMB data in Windows 11 and Server 2022 - Mon, Oct 4 2021
- Install Windows 11 in a virtual machine - Tue, Sep 28 2021
- IE to Edge migration: Redirect legacy web apps to Internet Explorer - Tue, Sep 21 2021
The built-in set command can only assign, change, or delete values of variables in the environment of cmd.exe. The common way to set user and system variables is through the graphical tool System Properties (sysdm.cpl > Advanced > Environment variables).
System properties - Environment variables
A more flexible alternative is setx, which can do more than just store constant values in environment variables. Unfortunately, you can’t leverage its powerful features in batch scripts. In its simplest form, you can use setx to assign a constant value to a variable. However, contrary to set, you don’t need an equals sign for this purpose: setx MACHINE HP. Instead of a constant, you can also assign the value of another environment variable. If you add the switch /m, the variable is set in the system environment and not just in the local environment of the current user.
Reading values from files or Registry keys ^
If you just want to assign constants to environment variables, you are better off with Group Policy Preferences because they allow you to do this task centrally for specific users and computers. The strength of setx is that it enables you to read data from files and the Registry and store those values in environment variables. This is quite easy with Registry keys because you read structured data. However, access is restricted to the hives below HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE. For instance, the following command determines the Word 2010 installation folder and stores it in the variable WP:
setx WP /K HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Word\InstallRoot\Path
Searching and parsing files ^
setx offers sophisticated techniques for reading information from files. Using delimiters you can partition a file into fields which you can directly access through coordinates. The following example reads the second column of the third row in a CSV file that uses semicolons as delimiters:
setx FIELD /F input.csv /A 2,1 /D ";"
The powerful parsing capabilities of setx even allow you to define coordinates relative to the first occurrence of a search term. The following example demonstrates how you can extract the host name rhino.acme.com for the IP address 126.96.36.199 from the file hosts.sam:
setx HOST /F hosts /R 0,1 "188.8.131.52" /D " "
Parsing features are rare in Windows command-line tools. They would be a welcome addition for batch scripts where you have to read data from files or from the Registry, test the values, and create file names using computed values. This fails because setx can’t write into the local environment of the command-line interpreter. System variables are only available in a new instance of cmd.exe, so you can’t use the variables in the batch script that created them.