I want to add a script to windows startup by writing a new value to Run registry key. I have the following code in python.
from _winreg import *
def setScriptAtStartup(
value_name,
bAdd,
script_path=None
):
'''
:param value_name: the name value to be used in registry
:param bAdd: TRUE = Add, FALSE = Remove
:param script_path: path to run at startup
:return:
'''
if bAdd and script_path == None:
return False
aReg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
print r"*** Writing to SOFTWARE\Microsoft\Windows\CurrentVersion\Run ***"
try:
aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", 0, KEY_WRITE)
if(bAdd):
SetValueEx(aKey, value_name, 0, REG_SZ, script_path)
else:
DeleteValue(aKey, value_name)
except EnvironmentError:
print "Encountered problems writing into the Registry..."
CloseKey(aKey)
CloseKey(aReg)
return
The problem is that when i call OpenKey function, it always raise EnvironmentError and I can't figure it out why. I have checked the path and it is a valid one. Additionaly, I have tried to open only SOFTWARE key and it fails again.
What can i do to fix this problem? Thank you