windowspowershellenvironment-variables

How to update environment variable on the same session (immediately) on powershell?


I would like to write some scripts on powershell, it involve using the environment variable on windows

here is the example of the script

test.ps1

setX number 456
echo $env:number

I found that $env:number cannot be updated immedately on the same session of powershell prompt. I need to reopen the powershell prompt. However, this would break my scripts How can i update the env variable immedately? In linux it is easy to do with EXPORT command, but for windows, it is a hazard...


Solution

  • In PowerSell environment variables are available through a provider. A provider is a way to manupulation all kind of tree containers. have à look at :

    Get-PSProvider
    

    Then drives are entities using these providers. have a look at

    Get-PSDrive
    

    You can see that it exists a drive called env

    You can try :

    Get-childItem env:
    

    to set an environment variables you can write :

    $env:mavar = "TESTJPB"

    To create more permanent environment variables (i.e., user-level or machine-level) you need to use the .NET Framework and the SetEnvironmentVariable method. For example, this command creates a user-level environment variable named TestVariable:

    [Environment]::SetEnvironmentVariable("mavar", "TESTJPB", "User")
    

    Have a look to this Microsoft article.