Reading Environment Variables

To read an environment variable in PowerShell, you can use the $env prefix. For example, to read the Path environment variable, use the following command:

$Mavariable = $env:Path
echo $Mavariable

This command assigns the value of the Path environment variable to the variable $Mavariable and then prints it to the console.

Writing Environment Variables

To write an environment variable that will only last for the duration of the current PowerShell session, use the following syntax:

$env:Path = "c:\windows"

This command temporarily sets the Path environment variable to c:\windows. The change will be discarded when you close the PowerShell session.

Writing Permanent Environment Variables

To permanently set an environment variable, use the [Environment]::SetEnvironmentVariable method. This method requires three parameters: the name of the variable, the value to set, and the target scope (User or Machine).

For example, to permanently set the Path environment variable for the entire machine, use the following command:

[Environment]::SetEnvironmentVariable("Path", "c:\windows", "Machine")

This command updates the Path environment variable and makes the change permanent across all sessions and users on the machine.

Example Script

Here is an example PowerShell script that reads the current Path variable, temporarily updates it, and then sets it permanently:

# Read the current Path variable
$currentPath = $env:Path
echo "Current Path: $currentPath"

# Temporarily set the Path variable
$env:Path = "c:\temporary"
echo "Temporary Path: $env:Path"

# Permanently set the Path variable
[Environment]::SetEnvironmentVariable("Path", "c:\windows", "Machine")
echo "Permanent Path set to c:\windows"

Save this script as a .ps1 file and run it in PowerShell to see the changes in action.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.