Environment variables

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Nick Chard Nick Chard 1 year, 10 months ago.

  • Author
    Posts
  • #21964
    Profile photo of Nick Chard
    Nick Chard
    Participant

    I'm struggling to add and remove environment variables with PowerShell

    First I ran this command

    New-Item -path env:MyTestEnv -Value 0

    Then

    gci env:

    This shows a list of environment variables, and MyTestEnv is listed

    From the command prompt I ran
    %MyTestEnv%
    '%MyTestEnv%' is not recognized as an internal or external command,
    operable program or batch file.

    So it seems like my variable has not been set.

    Next, I ran this command from PowerShell

    [Environment]::SetEnvironmentVariable["MyTestEnv", "0", "Machine"]

    And then from the command prompt

    %MyTestEnv%
    '0' is not recognized as an internal or external command,
    operable program or batch file.

    So now my variable has been set. Any ideas what the problem is here?

  • #21965
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    When you modify something in PowerShell's env: drive directly, you're modifying a Process environment variable. This will take effect in any child processes that you launch from that PowerShell window, but will not be persisted after PowerShell closes, nor will they apply to any processes that aren't children of that PowerShell window. This is the same as using the SET command in a batch file.

    [Environment]::SetEnvironmentVariable() , on the other hand, persists that setting by writing it to the registry (either in the HKEY_CURRENT_USER or HKEY_LOCAL_MACHINE hives, depending on what you passed in for the third argument.)

  • #21988
    Profile photo of Nick Chard
    Nick Chard
    Participant

    Thanks for that explanation Dave – makes perfect sense. So it looks like I have to use the .Net framework Environment class if I want to set a persistent machine wide environment variable

You must be logged in to reply to this topic.