Situatie
PowerShell Environmental variable stores the Windows Operating System information like the Operating System path where it installed, System Drive, User profile path, number of Processors, etc. They can be used by another program or the child parent processes because they are easier to work.Setting the environment variable using the PowerShell is the easy way, and for that, we can use either the simple variable appending method, the .Net method, or the Set-Item cmdlet.
Solutie
Pasi de urmat
Below are the methods to set the environment variable.
By adding/appending in a variable
$Env:<variable-name> = "<new-value>"
The above command syntax creates a new environment variable with the value specified. To append the variable, use the (+) symbol.
$Env:<variable-name> += "<new-value>"
Using Set-Item cmdlet
Below command, syntax sets the existing variable name. We can also create a new variable without providing the existing variable name inside the Value parameter.
Set-Item -Path Env:<variable-name> -Value ($Env:<variable-name> + ";<new-value>")
Using the Set-Content Method
In this method, we can use this cmdlet directly by providing a path of the environment variable or by setting the location first to the environment path and then changing the variable directly.
Set-Content -Path env:<variable-name> -Value "ValueName"
Using the .Net class method
[Environment]::SetEnvironmentVariable(String, String)
The above command creates, modifies, or deletes the environment variable stored in the current process.
[Environment]::SetEnvironmentVariable(String, String,EnvironmentVariableTarget)
The above command creates, modifies, or deletes the environment variable stored in the current process or the Windows operating system registry key.
How does the Environment variables work in Windows?
Environment variables are stored in the variable called Env, and it can be accessed using Get-ChildItem (alias: dir) to get all the values stored in the variable. For example:
Get-ChildItem Env:
If you notice in the above command, the environment variable ends with the (:) symbol, and it indicates the drive symbol but Env: is the specific drive, and you can get all the drives associated in the current session using the Get-PSDrive command.
value
Get-PSDrive
You can notice that Env is present in the Name, and so we can access it using the Drive symbol with Env: value similar to registry values. To check all the drives attached in the current session, use the Get-PSProvider command.
Get-PSProvider
To set the environment variable persistently on Windows OS, you need to use Computer Properties -> Advanced System Settings -> Advanced Tab -> Environment Variable. You can add or edit the existing environment variable in the user or Machine scope, and then windows write this variable in the registry to make a permanent change, and it remains even after windows restarts.
Leave A Comment?