🎓 A1Learner
🔍
0 of 47 lessons completed

PowerShell Environment Drive

The Env: drive is a drive that holds named values that programs can read. It lets a script store a value, read it back, and remove it again.

Set a variable and read it back

Set the variable in the script. Then read its Value back from the Env: drive.

$env:PSINT_DEMO = 'demo-value'
(Get-Item Env:PSINT_DEMO).Value
Test-Path Env:PSINT_DEMO

Change a variable value

Setting the same name again replaces the old value. Read it back to see the new value.

$env:PSINT_DEMO = 'first'
$env:PSINT_DEMO = 'second'
(Get-Item Env:PSINT_DEMO).Value

Remove a variable and prove it is gone

Remove-Item deletes the entry. Test-Path then returns False, which proves the absence.

$env:PSINT_DEMO = 'demo-value'
Remove-Item Env:PSINT_DEMO
Test-Path Env:PSINT_DEMO

Example

$env:PSINT_DEMO = 'demo-value'
(Get-Item Env:PSINT_DEMO).Value
Remove-Item Env:PSINT_DEMO
Test-Path Env:PSINT_DEMO

Key points

  • Environment variable: a named value that programs can read.
  • Env: drive: the drive that holds environment variables as items.
  • Use $env:NAME to set an environment variable in a script.
  • Use Get-Item Env:NAME to read one environment variable entry.
  • Use Remove-Item Env:NAME to delete an environment variable.
  • Use Test-Path Env:NAME to check whether an environment variable exists.

In this example, the script sets PSINT_DEMO to demo-value, reads its Value back from the Env: drive, removes the entry, and then Test-Path returns False to prove the entry is gone.

Note

list only the variables you set, because a full Env: listing changes with each machine.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

After Remove-Item Env:PSINT_DEMO runs, what does Test-Path Env:PSINT_DEMO return?