0
0
PowerShellscripting~5 mins

Environment variables in PowerShell

Choose your learning style9 modes available
Introduction
Environment variables store information that programs and scripts can use to work properly. They help scripts know about the system or user settings without hardcoding values.
You want to get the current user's home folder path in a script.
You need to check or set the system's PATH to run programs.
You want to store a secret key or configuration that your script can access.
You want to make your script work on different computers without changing code.
You want to temporarily change a setting for a program run by your script.
Syntax
PowerShell
Get-ChildItem Env:\
$env:VARIABLE_NAME = "value"
$env:VARIABLE_NAME
Use Get-ChildItem Env:\ to list all environment variables.
Use $env:VARIABLE_NAME to read or set an environment variable.
Examples
Lists all environment variables available in the current session.
PowerShell
Get-ChildItem Env:\
Shows the current user's name stored in the environment variable USERNAME.
PowerShell
$env:USERNAME
Sets a new environment variable MY_VAR to 'Hello' and prints it.
PowerShell
$env:MY_VAR = "Hello"
Write-Output $env:MY_VAR
Sample Program
This script sets a new environment variable GREETING, prints it, and then shows the current user and home path from existing environment variables.
PowerShell
$env:GREETING = "Hello, PowerShell!"
Write-Output "The greeting is: $env:GREETING"

# List a few important environment variables
Write-Output "User: $env:USERNAME"
Write-Output "Home Path: $env:HOMEPATH"
OutputSuccess
Important Notes
Environment variables set in a script only last for that session unless saved permanently.
Use $env:VARIABLE_NAME = $null to remove an environment variable in the current session.
Be careful not to overwrite important system environment variables.
Summary
Environment variables store system or user information accessible to scripts.
Use $env:VARIABLE_NAME to read or write environment variables in PowerShell.
They help make scripts flexible and adaptable to different environments.