Jump to content
tonycst

Please help with registry

Recommended Posts

tonycst

I was trying to get the EnvSet() but people on the internet say it only works while script runs.

So i went doing it with the registry instead.

Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

I accidentally replaced "path" key with my own value.

2 questions
What is the default value in Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\path ? for Win10X64 ?

 

Second question is:

Why this does not work ?

;AutoIt Version: 3.3.14.1
#RequireAdmin
#include <File.au3>
$INI = @ScriptDir & "\APy2EXE.ini"
$DefaultPipDir = @UserProfileDir & "\AppData\Local\Programs\Python"
If FileExists (IniRead ($INI,"Settings","Pythonpip","")) = 0 Then
    $Pythonpip = FileOpenDialog("Select python SCRIPTS folder",$DefaultPipDir,"pip.exe (pip.exe)","","pip.exe")
    If $Pythonpip = "" Then
        MsgBox(16,"Error","No path selected. Try again")
        Exit
    Else
        IniWrite ($INI,"Settings","Pythonpip",$Pythonpip)
    EndIf
Else
    $Pythonpip = IniRead ($INI,"Settings","Pythonpip","")
    $DirOnly = StringTrimright ($Pythonpip,7) ;just remove the pip.exe
EndIf
EnvUpdate()
$Get = EnvGet ("Path")
If StringInStr ($Get,$DirOnly) = 0 Then
    _SetEnv()
Else
    MsgBox(64,"Information", "System environmental variable already exists")
EndIf
Func _SetEnv()
    $Set = EnvSet ("Path",$Get & $DirOnly & ";"); so i dont delete anything.
    EnvUpdate()
    If $Set = 0 Then
        MsgBox (16,"Error","Unable to set system variable." & @CRLF & "Try running this program as administrator")
    Else
        MsgBox (64,"Information","System Variable was added")
    EndIf
EndFunc

 

Edited by tonycst

Share this post


Link to post
Share on other sites
tonycst

for some reasons my code says that variable is written, but i dont see it when i open computer system properties or looking into registry under

Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

 

EnvUpdate()
$Get = EnvGet ("Path")
MsgBox (0,'',$Get)

This code says that every variable is STILL there even after i went and manually deleted it from both system properties and registry
What am i missing ?

I tried that same code on my other computer that runs autoit 3.3.14.2 (vs 3.3.14.1) and it worked the first time.

Edited by tonycst

Share this post


Link to post
Share on other sites
Subz

EnvSet Help

Quote

A environment variable set in this way will only be accessible to programs that AutoIt spawns (Run(), RunWait()). Once AutoIt closes, the variables will cease to exist.

I always use the following code for setting environment variables:

Example:

#RequireAdmin
#include <EnvUpdate.au3>

Local $sAddPath = "C:\Data"
Local $sEnvPath = EnvGet("Path")
    If $sEnvPath <> "" And StringRight($sEnvPath, 1) <> ";" Then $sEnvPath &= ";"
MsgBox(0, "Env Path Original", $sEnvPath)

If StringInStr($sEnvPath, $sAddPath) Then Exit MsgBox(0, "Env Path Updated", $sAddPath & ' already added to Env "Path".')
_EnvUpdate("Path", $sEnvPath & $sAddPath & ";", False, True)

$sEnvPath = EnvGet("Path")
EnvUpdate()
MsgBox(0, "Env Path Updated", $sEnvPath)

EnvUpdate.au3 UDF

#include-once
; #INDEX# =======================================================================================================================
; Title .........: Environment Update
; AutoIt Version.: 3.2.12++
; Language.......: English
; Description ...: Refreshes the OS environment.
; Author ........: João Carlos (jscript)
; Support .......: trancexx, PsaltyDS, KaFu
; ===============================================================================================================================

; #CURRENT# =====================================================================================================================
;_EnvUpdate
; ===============================================================================================================================

; #INTERNAL_USE_ONLY# ===========================================================================================================
; ===============================================================================================================================

; #VARIABLES# ===================================================================================================================
Global $MAX_VALUE_NAME = 1024
Global $HWND_BROADCAST = 0xffff
Global $WM_SETTINGCHANGE = 0x001A
Global $SMTO_ABORTIFHUNG = 0x0002
Global $SMTO_NORMAL = 0x0000
Global $MSG_TIMEOUT = 5000

; #Example# =====================================================================================================================
;~ _EnvUpdate("VERSION", "7.07.0110.2600")
;~ MsgBox(4096, @error, EnvGet("VERSION"))
;~ _EnvUpdate("VERSION", "", True, True)
;~ MsgBox(4096, @error, EnvGet("VERSION"))
; ===============================================================================================================================

; #FUNCTION# ====================================================================================================================
; Name...........: _EnvUpdate
; Description ...: Refreshes the OS environment.
; Syntax.........: _EnvUpdate( ["envvariable" [, "value" [, CurrentUser [, Machine ]]]] )
; Parameters ....: envvariable  - [optional] Name of the environment variable to set. If no variable, refreshes all variables.
;                  value        - [optional] Value to set the environment variable to. If a value is not used the environment
;                                   variable will be deleted.
;                  CurrentUser  - [optional] Sets the variable in current user environment.
;                  Machine      - [optional] Sets the variable in the machine environment.
; Return values .: Success      - None
;                  Failure      - Sets @error to 1.
; Author ........: João Carlos (jscript)
; Support .......: trancexx, PsaltyDS, KaFu
; Modified.......:
; Remarks .......:
; Related .......:
; Link ..........;
; Example .......; _EnvUpdate("TEMP", @SystemDir & "TEMP", True, True)
; ===============================================================================================================================
Func _EnvUpdate($sEnvVar = "", $vValue = "", $fCurrentUser = True, $fMachine = False)
    Local $sREG_TYPE = "REG_SZ", $iRet1, $iRet2

    If $sEnvVar <> "" Then
        If StringInStr($sEnvVar, "\") Then $sREG_TYPE = "REG_EXPAND_SZ"
        If $vValue <> "" Then
            If $fCurrentUser Then RegWrite("HKCU\Environment", $sEnvVar, $sREG_TYPE, $vValue)
            If $fMachine Then RegWrite("HKLM\System\CurrentControlSet\Control\Session Manager\Environment", $sEnvVar, $sREG_TYPE, $vValue)
        Else
            If $fCurrentUser Then RegDelete("HKCU\Environment", $sEnvVar)
            If $fMachine Then RegDelete("HKLM\System\CurrentControlSet\Control\Session Manager\Environment", $sEnvVar)
        EndIf
        ; http://msdn.microsoft.com/en-us/library/ms686206%28VS.85%29.aspx
        $iRet1 = DllCall("Kernel32.dll", "BOOL", "SetEnvironmentVariable", "str", $sEnvVar, "str", $vValue)
        If $iRet1[0] = 0 Then Return SetError(1)
    EndIf
    ; http://msdn.microsoft.com/en-us/library/ms644952%28VS.85%29.aspx
    $iRet2 = DllCall("user32.dll", "lresult", "SendMessageTimeoutW", _
            "hwnd", $HWND_BROADCAST, _
            "dword", $WM_SETTINGCHANGE, _
            "ptr", 0, _
            "wstr", "Environment", _
            "dword", $SMTO_ABORTIFHUNG, _
            "dword", $MSG_TIMEOUT, _
            "dword_ptr*", 0)

    If $iRet2[0] = 0 Then Return SetError(1)
EndFunc   ;==>_EnvUpdate

 

Share this post


Link to post
Share on other sites
orbs

@tonycst,

first, you are correct that environment variables last throughout the script runtime and do not survive script termination. which is exactly what they are good for - use them for that purpose, not for anything else.

second, the environment is not global. when your script begins, it inherits a copy of the environment and is working with it. this is why you should not expect environment changes to survive the script termination. moreover, when you Run() a @comspec statement, that creates yet another environment session, and changes made in that do not propagate upward to the calling script.

in short - you are using the wrong place to store your data. i advise you describe why you are using the environment variable to store your data,  so we may suggest a more appropriate storage facility.

Share this post


Link to post
Share on other sites
tonycst

If those functions dont work (stock once) why are they there to begin with ?

I happened to find right after i thought "it worked on another computer" that it didnt work. Instead two computers with same variables return opposite values.

My latest code i ran on both machines return opposite results.

#include <File.au3>
$INI = @ScriptDir & "\APy2EXE.ini"
$DefaultPipDir = @UserProfileDir & "\AppData\Local\Programs\Python"
If FileExists (IniRead ($INI,"Settings","Pythonpip","")) = 0 Then
    $Pythonpip = FileOpenDialog("Select python SCRIPTS folder",$DefaultPipDir,"pip.exe (pip.exe)","","pip.exe")
    If $Pythonpip = "" Then
        MsgBox(16,"Error","No path selected. Try again")
        Exit
    Else
        IniWrite ($INI,"Settings","Pythonpip",$Pythonpip)
    EndIf
EndIf

$Pythonpip = IniRead ($INI,"Settings","Pythonpip","") ;re initialization
$DirOnly = StringTrimRight ($Pythonpip,7) ;remove pip.exe from the string above to just the the path wiht  \ i need
EnvUpdate()
$Get = EnvGet ("Path")
ConsoleWrite ($Get& @CRLF)
If StringInStr ($Get,$DirOnly) = 0 Then ;no variable. need to add it
    _SetEnv()
Else
    MsgBox(64,"Information", "System environmental variable already exists")
EndIf

Func _SetEnv()
    $Set = EnvSet ("Path",$Get & ";" & $DirOnly)
    EnvUpdate()
    If $Set = 0 Then
        MsgBox (16,"Error","Unable to set system variable." & @CRLF & "Try running this program as administrator")
    Else
        MsgBox (64,"Information","System Variable was added")
    EndIf
EndFunc

Laptop says that it does not exist and my desktop computer says it does.

But it does not exists in either cases.

 

 

Thanks for your help, i will try your code asap.

Share this post


Link to post
Share on other sites
tonycst
2 minutes ago, orbs said:

@tonycst,

in short - you are using the wrong place to store your data. i advise you describe why you are using the environment variable to store your data,  so we may suggest a more appropriate storage facility.

I am trying to create environmental variable that is required by external console application to compile python script to windows executable.
This is the process i am trying to automate.

This is too much work going back and worth. I wanted to make something that will let me do it with couple of clicks.

Edited by tonycst

Share this post


Link to post
Share on other sites
tonycst

I think i found my problem.
$Get = EnvGet ("Path") returns "True" instead of data in that variable.

 

So how to i read the data in the  "Path" variable ?

Edited by tonycst

Share this post


Link to post
Share on other sites
orbs
2 minutes ago, tonycst said:

If those functions dont work (stock once) why are they there to begin with ?

 

1 minute ago, tonycst said:

I am trying to create environmental variable that is required by external console application ...

the latter quote is the answer to the former. you set environment variable in your script in order to call a depending application - which should inherit the environment (yet not propagate changes back to the calling script).

how exactly are you calling the console application?

Share this post


Link to post
Share on other sites
Subz

Did you try the script in my post above?

Share this post


Link to post
Share on other sites
tonycst

Well i have not gotten to calling the console app yet. I am still struggling with the Env.
Right now i am lost with EnvGet() returning True, instead of the value
C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\

I need to read the value, not to check for the existence of the "Path" name :(
Not sure how to do that.

Share this post


Link to post
Share on other sites
orbs

EnvGet returns a string, not boolean... :huh2:  what is the content of your path variable?

Share this post


Link to post
Share on other sites
tonycst

lol i was testing it wrong
I was doing this MsgBox (0,'',$Get = EnvGet ("Path")) so that returned true. idiot :)

Share this post


Link to post
Share on other sites
orbs

is "pyinstaller.exe" the console application you need to call? if so, have you noticed its command line arguments? would the one titled --paths be of any use?

Share this post


Link to post
Share on other sites
Subz

Basically he is trying to add the environment variable to ...\Pythonxx\Scripts so when you run Python you can use the Python Package Manager (PIP) without typing out the full path to pip.exe.

See https://github.com/BurntSushi/nfldb/wiki/Python-&-pip-Windows-installation

This needs to be a static variable, as I mentioned you need to use either the code I printed above or something like below to configure environment variables, you could also use WMI, personally I've found the UDF above to work on WinXP, Win7 and Win10 x86/x64 so would suggest using that:

#RequireAdmin
#include <"
Local $sAddPath = "C:\Data"
Local $sEnvPath = EnvGet("Path")
    If $sEnvPath <> "" And StringRight($sEnvPath, 1) <> ";" Then $sEnvPath &= ";"
MsgBox(0, "Env Path Original", $sEnvPath)

If StringInStr($sEnvPath, $sAddPath) Then Exit MsgBox(0, "Env Path Updated", $sAddPath & ' already added to Env "Path".')
_SetEnv("Path", $sEnvPath & $sAddPath & ";", "SYSTEM")

$sEnvPath = EnvGet("Path")
EnvUpdate()
MsgBox(0, "Env Path Updated", $sEnvPath)


Func _SetEnv($_sEnvVariable, $_sEnvValue, $_sEnvType = "USER")
    Local $objShell = ObjCreate("WScript.Shell")
    Local $objEnv = $objShell.Environment($_sEnvType)
        $objEnv($_sEnvVariable) = $_sEnvValue
EndFunc

 

Share this post


Link to post
Share on other sites
tonycst

I agree, but just using your UDF does not help me learn anything.

I am puzzled with this:

If StringInStr ($Get,$DirOnly) = 0 Then ;no variable. need to add it
    MsgBox(64,"Information", "No Variable Value is set.")
    _SetEnv()
Else
    MsgBox(64,"Information", "System environmental variable already exists")
EndIf

It keeps telling me that the entry already exist.
Where does it exist, in RAM ?
Its not in the windows Edit Env vars dialog either or in registry keys.
Where is it ? Why does it keep telling me that its already exist ?
Maybe something wrong with the string i am searching for ? Maybe my string is too long ?
Here is the string i am searching for using StringInStr
C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\Scripts\pip.exe
is it too long maybe ?

screenshot.jpg

Share this post


Link to post
Share on other sites
tonycst

found my problem
Problem was StringInStr was receiving too many characters to find inside the string.
I shortened the search string and started getting progress.

Thank you guys, i learned something today, something that not mentioned in the help file (character limit) for StringInStr()
Maybe its posted elsewhere who knows.

Edited by tonycst

Share this post


Link to post
Share on other sites
Subz

Now aware of any limits, my Path has 1355 characters and I can search for "C:\Users\UserName\AppData\Local\Programs\Python\Python36\Scripts" without any issues.

Share this post


Link to post
Share on other sites
tonycst

Ok

I manually entered value into the system so its there.
When i run this code, it says its not there.

$String = "Python"
$Env = EnvGet ("Path")
EnvUpdate()
If StringInStr ($Env,$String) = 0 Then
    MsgBox(0,'','no string')
Else
    MsgBox (0,'','yes string')
EndIf

Look at the picture, its clearly there. I am looking for a simple word and its not finding it.

Am i doing it the wrong way ?

New Bitmap Image.jpg

Share this post


Link to post
Share on other sites
tonycst

screw this envget. I just went straight into the registry.

$Get = RegRead ("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment","Path")
If StringInStr ($Get,$DirOnly) = 0 Then
    RegWrite ("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment","Path","REG_SZ",$Get & $DirOnly)
    MsgBox (64,"Information","System variable value has been set")
Else

This works perfect.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×