PowerShell command to add the environment variable

Varma 1,495 Reputation points
2024-02-03T14:23:14.3433333+00:00

I want to add below 2 environment variables using PowerShell command. I have done it manually but now and down the line I want to add environment variables in VM using PowerShell commands, Please suggest User's image

User's image

Azure Virtual Machines
Azure Virtual Machines
An Azure service that is used to provision Windows and Linux virtual machines.
9,013 questions
Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Andreas Baumgarten 123.4K Reputation points MVP Volunteer Moderator
    2024-02-03T15:29:02.25+00:00

    Hi @Varma ,

    system variabeles can be set in PowerShell like this (admin permission is required to modify/add system variables !):

    [Environment]::SetEnvironmentVariable("MYNewVariable", "MyTestValue", "Machine")
    

    An existing variable can be read via PowerShell like this:

    [Environment]::SetEnvironmentVariable("MYNewVariable", "MyTestValue", "Machine")
    [Environment]::GetEnvironmentVariable("Path","Machine")
    

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards

    Andreas Baumgarten


  2. Andreas Baumgarten 123.4K Reputation points MVP Volunteer Moderator
    2024-02-03T17:37:08.66+00:00

    Hi @ Varma,

    this looks fine for me:

    [Environment]::SetEnvironmentVariable("JAVA_HOME", "C:\Program files\Java\jdk-21", "Machine")
    

    To add %JAVA_HOME% to your PATH variable you need to read the current value of the PATH variable and add the %JAVA_HOME% value. Something like this (NOT TESTED):

    $addValue = "%JAVA_HOME%"
    $oldvalues = [Environment]::GetEnvironmentVariable("PATH","Machine")
    $newValue = $oldValues + " `r`n "+ $addValue
    [Environment]::SetEnvironmentVariable("PATH", "$newValue", "Machine")
    "Machine")
    

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards

    Andreas Baumgarten


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.