19

As above.

I tried (inside powershell terminal with run as admin)

[System.Environment]::SetEnvironmentVariable('ResourceGroup','AZ_Resource_Group')

and the variable is only available for that window. If I open another powershell window or restart my PC, the variable is lost.

Thanks

4
  • Why don’t you create the system variable through the GUI?
    – Ramhound
    Jul 5, 2022 at 2:33
  • 6
    What a funny question to ask about PowerShell in a site for Super Users. Apr 25, 2023 at 12:21
  • 1
    @KevinBuchan what make it fun?
    – Ooker
    May 15, 2023 at 5:23
  • 1
    @Ooker I think Kevin meant that Ramhound's question about using the GUI was funny, since this site includes a lot of people who need answers that can be run as part of a script. Mar 4 at 15:23

1 Answer 1

31

Please specify the scope when setting the variable:

Saving environment variables with SetEnvironmentVariable

On Windows, you can specify a scope for the SetEnvironmentVariable method as the third parameter to set the environment variable in that scope. The machine and user scopes both persist outside of the current process, allowing you to save a new or changed environment variable.

[System.Environment]::SetEnvironmentVariable('ResourceGroup','AZ_Resource_Group', 'Machine')
[System.Environment]::SetEnvironmentVariable('ResourceGroup','AZ_Resource_Group', 'User')
2
  • 1
    Anyone else is getting this error? (Run PowerShell as administrator will fix it) Exception calling "SetEnvironmentVariable" with "3" argument(s): "Requested registry access is not allowed." Feb 5, 2023 at 15:41
  • 4
    @HafizTemuri Good call. In order for this to work, you need to be running PowerShell as an administrator. (In my case it "worked" but silently failed, i.e. I reopen PS and the environment variable is unset.) Good grief...
    – Andrew
    May 16, 2023 at 21:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .