WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

Environment

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

Set System Environment Variable


Question:

Is there a way in WinBatch to set a System environment variable in Windows NT/2000/XP? (Without using SETX.EXE.)

Answer:

Just update the registry.
#DefineFunction EnvUpdate ()
   ; Similar effect as logging off and then on again.
   ; For example, changes to the %path% environment might not take effect
   ; until you call EnvUpdate (or you logoff/reboot).
   IntControl(59,-1,"Environment",0,0)
   Return 1
#EndFunction

; Initialize variables
keyhandle = @REGMACHINE
envkeyname = 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
envvalue = '[PATH]'
newdata = 'c:\TEMP'

; Read current the System Path
currentenvpath = RegQueryExpSz( keyhandle, envkeyname:envvalue  )
Pause('Current System PATH', currentenvpath)

; Update the System Path
newpath = currentenvpath:';':newdata ; IMPORTANT APPEND NEW DATA TO COMPLETE PATH
RegSetExpSz( keyhandle, envkeyname:envvalue,newpath )

; Read updated the System Path
currentenvpath = RegQueryExpSz( keyhandle, envkeyname:envvalue  )
Pause('Updated System PATH', currentenvpath)

; Update System Environment to reflect changes withourt reboot
Test = EnvUpdate ()
If Test
   Message ("Result","Environment Refresh Successful")
Else
   Message ("Result","Environment Refresh Unsuccessful")
EndIf
Exit

See Also: http://techsupt.winbatch.com/webcgi/webbatch.exe?techsupt/nftechsupt.web+WinBatch/Environment+NT~Environment~variables.txt

User reply:

Thanks, that did it. I am attaching a complete script that uses this information. Someone else might find it useful.
SETCDROMDRV.WBT
Sets Sys. Env. var. at every login/boot 

;-------------------------------------------------------------------------------------------
; CD-ROM Drive Letter Environment Variable Setting Script - v.1.0.0.1
; Author: Donald T. Gates
; Updated by: Donald T. Gates
; Last Updated: 2003-10-30
; Script Name: $Id$
; Change Log
; v.1.0.0.1 (Donald T. Gates) 2003-11-03
;           Completed comments and provisions for commandline paramters.
; v.1.0.0.0 (Donald T. Gates) 2003-10-30
;           Created Script.
;-------------------------------------------------------------------------------------------


;-------------------------------------------------------------------------------------------
;                                  Application Description.

; Applicable Operating Systems: Windows NT 3.5, 3.51, 4.0, 2000, and XP.

; This short script sets a system environment variable to the drive letter of the CD-ROM drive.
; The script then forces an update of the Windows environment to make the change visible to all (running) applications.
; Note, this will NOT affect any open command prompt (CMD.EXE) windows.
; (But any windows opened after execution of this script will show the change to the (new) environment variable.)

; The script will accept the following parameters.
; Note: If the parameters conflict, the script will do nothing and return an error to the caller.
;		-s (1)		Create environment variable only. An error is returned if this fails.
;		-i (2)		Create environment variable, install the application in the Windows directory and
;							set the Run key in the registry to execute the application at each reboot/login.
;							The execution of the script may fail if the user does not have the permission to
;							set the run key. In this case, only the environment variable will be created.
;							The script will return an error.
;		-u (3)		Remove environment variable and if installed, uninstall the application.
;							The script will return an error if the environment variable cannot be removed,
;							or the application cannot be uninstalled.
;		-? (4)		Displays message box showing command line parameters and then exits application.
;		All other parameters are ignored by the application.
;-------------------------------------------------------------------------------------------


;-------------------------------------------------------------------------------------------
;								Start - Local Subroutine Definition Section
;-------------------------------------------------------------------------------------------

;-------------------------------------------------------------------------------------------
; This subroutine processes the commandline parameters.
; Subroutine CheckParams
;					Returns @True if the parameter is valid, with the RunOption = 1, 2, 3, or 4
;					Returns @False if the parameter is invalid, with the RunOption = 0.

#DefineSubroutine CheckParams()

RunOption = 0

if param0 > 1
		return @False
	else
		if param0 == 0					; No commandline parameters - treated the same as "-?".
			RunOption = 4
		else
			StrLower(param1)
			if param1 == "-s"			; Create environment variable only.
				RunOption = 1
			else
				if param1 == "-i"			; Create environment variable, install the application in the Windows directory and
					RunOption = 2		; set the Run key in the registry to execute the application at each reboot/login.
				else
					if param1 == "-u"		; Remove environment variable and if installed, uninstall the application.
						RunOption = 3
					else
						if param1 == "-?"	; Displays message box showing command line parameters and then exits application.
							RunOption = 4
						else
							return @False
						endif
					endif
				endif
			endif
		endif
	endif

	return @True

#EndSubroutine
;-------------------------------------------------------------------------------------------


;-------------------------------------------------------------------------------------------
;								End - Local Subroutine Definition Section
;-------------------------------------------------------------------------------------------


;-------------------------------------------------------------------------------------------
;											Start - Main Program
;-------------------------------------------------------------------------------------------

if CheckParams()
	wbpathname = IntControl (1004, 0, 0, 0, 0)	; Get full pathname of this script.
	root = StrLower(FileRoot(wbpathname))
	ext = StrLower(FileExtension(wbpathname))
	wbfilename = StrCat(root, ".", ext)

	inst_okay = @False
	cds = DiskScan(8) 							; Get a list of the CD-ROM drive letters.
	cd_drive = StrSub(cds, 1, 2)				; Get the first CD-ROM drive (w/o the backslash character).
	windir = ENVIRONMENT("SystemRoot")		; Get path to WINNT directory.

	select RunOption

		; Just set the environment variable.
		case 1
			reg_okay = RegSetExpSz (@REGMACHINE, "SYSTEM\CurrentControlSet\Control\Session Manager\Environment[cd]", "%cd_drive%")
			if reg_okay
				inst_okay = @True
			endif 
		break

		; Set environment variable, copy this executeable to the WINNT directory and set Run registry key.
		case 2
			reg_okay = RegSetExpSz (@REGMACHINE, "SYSTEM\CurrentControlSet\Control\Session Manager\Environment[cd]", "%cd_drive%")
			if reg_okay
				copy_okay = FileCopy ("%wbpathname%", "%windir%", @False)	; Copy this script into the WINNT directory.
				if copy_okay
					reg_okay = RegSetEx (@REGMACHINE, "SOFTWARE\Microsoft\Windows\CurrentVersion\Run[Set CD-ROM Letter]", "%windir%\%wbfilename%", ",", 1)
					if reg_okay
						inst_okay = @True
					else ; For some reason, the final setting of the registry key failed. Undo the current changes.
						FileDelete ("%windir%\%wbfilename%")
						RegDelValue (@REGMACHINE, "SYSTEM\CurrentControlSet\Control\Session Manager\Environment[cd]")
					endif
				else ; For some reason, the copy of the executeable failed. Undo the current changes.
					RegDelValue (@REGMACHINE, "SYSTEM\CurrentControlSet\Control\Session Manager\Environment[cd]")
				endif
			endif
		break

		; Remove environment variable, and if installed, the Run key in the registry and uninstall the application.
		case 3
			RegDelValue (@REGMACHINE, "SOFTWARE\Microsoft\Windows\CurrentVersion\Run[Set CD-ROM Letter]")
			FileDelete ("%windir%\%wbfilename%")
			RegDelValue (@REGMACHINE, "SYSTEM\CurrentControlSet\Control\Session Manager\Environment[cd]")
			inst_okay = @True
		break

		; Displays message box showing command line parameters and then exits application.
		case 4
			txt = StrCat ("setcdromdrv.exe -s -i -u -?", @crlf)
			txt = StrCat (txt, "    -s  Set system environment variable 'CD' to CD-ROM drive letter", @crlf)
			txt = StrCat (txt, "    -i  Set variable and install app to run at each login/reboot", @crlf)
			txt = StrCat (txt, "    -u  Remove variable and app", @crlf)
			txt = StrCat (txt, "    -?  Display this dialog box")
			Message ("Set CD-ROM Drive Letter Environment Variable", txt)
		break
	end select


	; if (un)installation was successful, force update of system environment.
	if inst_okay
		IntControl(59, -1, "Environment", 0, 0)
	endif 
	
else
	return 1
endif

return 0
;-------------------------------------------------------------------------------------------
;											End - Main Program
;-------------------------------------------------------------------------------------------

Article ID:   W15940
File Created: 2014:07:18:09:51:38
Last Updated: 2014:07:18:09:51:38