7

I am stuck on a issue. I am trying to set user-environment variables using PowerShell:

[Environment]::SetEnvironmentVariable($key,$value,'User')

But when I look into the registry I can see the new entry is of type REG_SZ.

I would like it to be of type REG_EXPAND_SZ.

Can someone help me with this problem?

0xC0000022L
  • 20,597
  • 9
  • 86
  • 152
ajax
  • 317
  • 8
  • 17
  • 1
    btw, you should be using double quotes to delimit your powershell variables. if you don't, they will be treated as literals; you will have $key as the key name instead of the _value_ of $key as the name. – x0n Jul 02 '12 at 20:19
  • The question has been edited to address @x0n's astute observation. – Tim Lewis Mar 26 '13 at 18:04

2 Answers2

10

Use the Microsoft.Win32 namespace for Registry methods. To set the data type, use RegistryValueKind enumeration. Like so:

[Microsoft.Win32.Registry]::SetValue("HKEY_CURRENT_USER\Environment","MyKey","1",[Microsoft.Win32.RegistryValueKind]::ExpandString)

User variables are located in HKEY_CURRENT_USER\Environment

System variables are located in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

0xC0000022L
  • 20,597
  • 9
  • 86
  • 152
vonPryz
  • 22,996
  • 7
  • 54
  • 65
  • I will immediately try it out and thanks for the quick reply really appreciated :-) – ajax Jul 02 '12 at 14:09
  • Wow ur solution was spot on hats off to you :-) But just one more question How can I do this for another user - for eg - I am logged as user A and want to set the user environment for User B ? – ajax Jul 03 '12 at 07:14
  • You don't access another user's registry easily. Consider what could happen if one can just insert arbitary keys to another user's, say, `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` location.Either run the script as User B via login script or the like, or use a system variable. – vonPryz Jul 03 '12 at 10:53
  • @ajax You could always load the hive of the other user, given you have the appropriate level of access. This way you can even "prime" the other users' environments. However, the usual way to achieve it would be to manipulate the system-wide environment instead. – 0xC0000022L Jun 27 '22 at 07:55
3
Set-ItemProperty HKCU:\Environment $key $value -Type ExpandString

Or golfed

sp hkcu:environment $key $value -t e

Set-ItemProperty sets Registry Value as String on some systems instead of DWord, why?

Community
  • 1
  • 1
Zombo
  • 1
  • 62
  • 391
  • 407