Job
Job

Reputation: 505

How to set environment variable can access anytime using powershell?

I have text file with this format 12345 . I want to set that value as environment variable that I can access it even the powershell closed. My expectation when I want to access that environment variable from command line, I just use this command : echo %ID% and I t will show 12345

$file = Get-Content .\file.txt
$Variable = "ID"
[Environment]::SetEnvironmentVariable("$Variable", "$file")

Update Code

I tried this, but I still cant get the environment variable with this command from command line : echo %ID%

$file = Get-Content .\file.txt
$Variable = "ID"

[Environment]::SetEnvironmentVariable("$Variable", "$file",1)
[Environment]::SetEnvironmentVariable("$Variable", "$file","User")

Upvotes: 1

Views: 1003

Answers (2)

Lee_Dailey
Lee_Dailey

Reputation: 7479

you need to specify the target environment. by default, that static method only sets the $Var/value pair for the current process. you likely want that for the current user, so use the 2nd method listed in the 1st link below with the target set to user. here are the doc pages ...

Environment.SetEnvironmentVariable Method (System) | Microsoft Docs
https://learn.microsoft.com/en-us/dotnet/api/system.environment.setenvironmentvariable?view=netframework-4.7.2

EnvironmentVariableTarget Enum (System) | Microsoft Docs
https://learn.microsoft.com/en-us/dotnet/api/system.environmentvariabletarget?view=netframework-4.7.2

Upvotes: 2

mjsqu
mjsqu

Reputation: 5452

The third argument to [Environment]::SetEnvironmentVariable allows you to choose the Environment Variable Target. The default is the current process, so calling with two arguments only makes the variable available to the current PowerShell session.

If you have permissions you can enable the Environment Variable at the machine level (2), either:

[Environment]::SetEnvironmentVariable("$Variable", "$file",2)
[Environment]::SetEnvironmentVariable("$Variable", "$file","Machine")

Or, just the user level (1), either:

[Environment]::SetEnvironmentVariable("$Variable", "$file",1)
[Environment]::SetEnvironmentVariable("$Variable", "$file","User")
  • The 'Machine Level' is HKEY_LOCAL_MACHINE in the registry.
  • The 'User Level' is HKEY_CURRENT_USER

https://learn.microsoft.com/en-us/dotnet/api/system.environmentvariabletarget?view=netframework-4.7.2

Upvotes: 2

Related Questions