0
0
PowerShellscripting~10 mins

Environment variables in PowerShell - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Environment variables
Start PowerShell Session
Access Environment Variables
Read or Modify Variable
Use Variable in Script or Command
End or Continue Session
This flow shows how PowerShell starts, accesses environment variables, reads or changes them, uses them in commands, and then continues or ends.
Execution Sample
PowerShell
Write-Output $Env:USERNAME
$Env:MYVAR = "Hello"
Write-Output $Env:MYVAR
This script prints the current username, sets a new environment variable MYVAR, then prints its value.
Execution Table
StepActionVariableValueOutput
1Read environment variable USERNAMEUSERNAMEUser123User123
2Set environment variable MYVARMYVARHello
3Read environment variable MYVARMYVARHelloHello
4End of script
💡 Script ends after printing MYVAR value.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
USERNAMEUser123User123User123User123
MYVARundefinedHelloHelloHello
Key Moments - 2 Insights
Why does $Env:MYVAR have no value before setting it?
Before step 2 in the execution_table, MYVAR is not set, so it is undefined. Only after step 2 it has the value 'Hello'.
Does changing $Env:MYVAR affect system-wide variables?
No, changes to $Env:MYVAR in the session only affect the current PowerShell session, not system-wide environment variables.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 1?
AUser123
BHello
C$Env:USERNAME
Dundefined
💡 Hint
Check the Output column at step 1 in the execution_table.
At which step does MYVAR get its value?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the Variable and Value columns in the execution_table.
If you remove step 2, what would be the output at step 3?
AHello
BUser123
Cundefined
DError
💡 Hint
Without setting MYVAR, it remains undefined as shown in variable_tracker before step 2.
Concept Snapshot
PowerShell environment variables use $Env:VAR_NAME syntax.
Read with $Env:VAR_NAME, set with $Env:VAR_NAME = "value".
Changes affect only current session.
Use them to store info like usernames or paths.
Unset variables are undefined.
Full Transcript
In PowerShell, environment variables are accessed using $Env: followed by the variable name. You can read a variable like $Env:USERNAME to get the current username. You can also set a variable by assigning a value, for example $Env:MYVAR = "Hello". This change only affects the current PowerShell session and does not change system-wide settings. When you print $Env:MYVAR after setting it, you see the new value. Before setting, the variable is undefined. This simple script shows reading and writing environment variables step by step.