简体   繁体   English

如何在Powershell的同一会话上(立即)更新环境变量?

[英]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 我想在Powershell上编写一些脚本,它涉及在Windows上使用环境变量

here is the example of the script 这是脚本的示例

test.ps1 test.ps1

setX number 456
echo $env:number

I found that $env:number cannot be updated immedately on the same session of powershell prompt. 我发现$ env:number不能在Powershell提示符的同一会话上立即更新。 I need to reopen the powershell prompt. 我需要重新打开Powershell提示。 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... 在Linux中,使用EXPORT命令很容易,但是对于Windows,则存在危险...

In PowerSell environment variables are available through a provider. 在PowerSell中,环境变量可通过提供程序获得。 A provider is a way to manupulation all kind of tree containers. provider是一种操纵所有树形容器的方法。 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 您可以看到它存在一个名为env的驱动器

You can try : 你可以试试 :

Get-childItem env:

to set an environment variables you can write : 设置环境变量,您可以编写:

$env:mavar = "TESTJPB" $ 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. 若要创建更多永久性环境变量(即,用户级别或机器级别),您需要使用.NET Framework和SetEnvironmentVariable方法。 For example, this command creates a user-level environment variable named TestVariable: 例如,此命令创建一个名为TestVariable的用户级环境变量:

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

Have a look to this Microsoft article. 看看这篇微软文章。

你有没有尝试过

[environment]::setenvironmentvariable() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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