Skip to content

PowerShell Environment Variable $env:

Environment variables in PowerShell store key-value pairs that define system settings. They are inherited from the local Windows operating system and can be accessed using the $env: prefix.

These variables store system-wide and user-specific values, that can be used to influence the behavior of applications and scripts.

Accessing $env:

There are several ways to access or use those variables.

List all values using 'get-childitem':

PowerShell
Get-Childitem env:
post17_1

Those environment variables are also stored in powershell provider driver (ps-drive):

PowerShell
Get-Psdrive Env # get informatinen

post17_2

Which means you can set this as location:

PowerShell
Set-Location Env: # set env: as working location
Get-Location # will print current location
Get-Childitem # get all item in current location

post17_3

Purpose

Environment variables provide a dynamic, flexible, and secure way to store and retrieve system-wide and user-specific settings. They help in automation, configuration management, security, and portability of scripts across multiple environments.

For me the main purpose is keeping my scripts dynamic and general usable:

Using $env: for Dynamic File Paths

Instead of hardcoding file paths, use $env:UserProfile to store logs in the user’s Documents folder.

PowerShell
start-transcript -path "$env:userprofile\documents\log1.log"
write-host "Test123"
stop-transcript
invoke-item "$env:userprofile\documents\log1.log" 

post17_4

Checking System Information for Conditional Execution

Run specific function if various conditions are met.

PowerShell
if($env:computername -like "DEV*" -and $env:os -like "Windows*"){
  Function AB
}else{
  Function CD
}

post17_5

Modifying

It is also possible to add or remove environment variables. The huge thing here is, variables can be set permanently system-wide!

Current session

Environment variables set this way exist only for the duration of the session.

Add variable:

PowerShell
$env:best_anime = 'One Piece'

post17_6

Remove variable:

PowerShell
remove-item env:\best_anime

Permanently system-wide

To persist changes beyond the session, modify system or user-level environment variables using:

Add variable:

PowerShell
# user-wide
[System.Environment]::SetEnvironmentVariable('Best_Anime', 'One Piece', 'User')
# system-wide
[System.Environment]::SetEnvironmentVariable('Best_Anime', 'One Piece', 'Machine')

post17_7

PowerShell
# user-wide
[System.Environment]::SetEnvironmentVariable('Best_Anime', $null, 'User')
# system-wide
[System.Environment]::SetEnvironmentVariable('Best_Anime', $null, 'Machine')

References

Microsoft Docs

Cheers!