Talk:Setting Environment Variables

From NSIS Wiki
Jump to navigationJump to search

Is this script compatible with Windows Vista ? Thank you.

Obsolete? Confused.

The article states that it is made obsolete by EnvVarUpdate except for win95 compatibility. I was a rather confused by this because EnvVarUpdate (which I also use) seems more suitable for appending/removing values from a directory path as opposed to just setting or deleting a plain environment variable. In the end, I wrote my own functions EnvVarSet / EnvVarUnset consistent to EnvVarUpdate In case someone is interested, append the following to EnvVarUpdate.nsh:

!macro _EnvVarSetConstructor EnvVarName Regloc EnvVarValue EnvVarExpand
  Push "${EnvVarName}"
  Push "${RegLoc}"
  Push "${EnvVarValue}"
  Push "${EnvVarExpand}"
  Call EnvVarSet
!macroend
!define EnvVarSet '!insertmacro "_EnvVarSetConstructor"'
 
!macro _unEnvVarSetConstructor EnvVarName Regloc EnvVarValue EnvVarExpand
  Push "${EnvVarName}"
  Push "${RegLoc}"
  Push "${EnvVarValue}"
  Push "${EnvVarExpand}"
  Call un.EnvVarSet
!macroend
!define un.EnvVarSet '!insertmacro "_unEnvVarSetConstructor"'
 
!macro _EnvVarUnsetConstructor EnvVarName Regloc
  Push "${EnvVarName}"
  Push "${RegLoc}"
  Push ""
  Push 0
  Call EnvVarSet
!macroend
!define EnvVarUnset '!insertmacro "_EnvVarUnsetConstructor"'
 
!macro _unEnvVarUnsetConstructor EnvVarName Regloc
  Push "${EnvVarName}"
  Push "${RegLoc}"
  Push ""
  Push 0
  Call un.EnvVarSet
!macroend
!define un.EnvVarUnset '!insertmacro "_unEnvVarUnsetConstructor"'
 
 
Var EVSName
Var EVSRegLoc
Var EVSValue
Var EVSExpand
 
!macro EnvVarSet UN
 
Function ${UN}EnvVarSet
 
  Pop $EVSExpand
  Pop $EVSValue
  Pop $EVSRegLoc
  Pop $EVSName
 
  ${If} $EVSRegLoc == HKLM
    ${If} $EVSValue == ""
      DeleteRegValue ${hklm_all_users} $EVSName
    ${Else}
      ${If} $EVSExpand == "1"
        DetailPrint "Set $EVSName = $EVSValue (Expanding)"
        WriteRegExpandStr ${hklm_all_users} $EVSName $EVSValue
      ${Else}
        DetailPrint "Set $EVSName = $EVSValue"
        WriteRegStr ${hklm_all_users} $EVSName $EVSValue
      ${EndIf}
    ${EndIf}
  ${ElseIf} $EVSRegLoc == HKCU
    ${If} $EVSValue == ""
      DeleteRegValue ${hkcu_current_user} $EVSName
    ${Else}
      ${If} $EVSExpand == "1"
        DetailPrint "Set $EVSName = $EVSValue (Expanding)"
        WriteRegExpandStr ${hkcu_current_user} $EVSName $EVSValue
      ${Else}
        DetailPrint "Set $EVSName = $EVSValue"
        WriteRegStr ${hkcu_current_user} $EVSName $EVSValue
      ${EndIf}
    ${EndIf}
  ${Else}
    DetailPrint 'ERROR: RegLoc is [$EVSRegLoc] but must be "HKLM" or HKCU"'
  ${EndIf}
 
  ; "Export" our change
  SendMessage ${HWND_BROADCAST} ${WM_WININICHANGE} 0 "STR:Environment" /TIMEOUT=5000
 
FunctionEnd
 
!macroend
 
!insertmacro EnvVarSet ""
!insertmacro EnvVarSet "un."

Froesccn 13:30, 12 February 2009 (UTC)