简体   繁体   中英

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...

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 (ie, 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.

你有没有尝试过

[environment]::setenvironmentvariable() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM