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':

Those environment variables are also stored in powershell provider driver (ps-drive):
Which means you can set this as location:
Set-Location Env: # set env: as working location
Get-Location # will print current location
Get-Childitem # get all item in current location
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.
start-transcript -path "$env:userprofile\documents\log1.log"
write-host "Test123"
stop-transcript
invoke-item "$env:userprofile\documents\log1.log"
Checking System Information for Conditional Execution
Run specific function if various conditions are met.
if($env:computername -like "DEV*" -and $env:os -like "Windows*"){
Function AB
}else{
Function CD
}
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:
Remove variable:
Permanently system-wide
To persist changes beyond the session, modify system or user-level environment variables using:
Add variable:
# user-wide
[System.Environment]::SetEnvironmentVariable('Best_Anime', 'One Piece', 'User')
# system-wide
[System.Environment]::SetEnvironmentVariable('Best_Anime', 'One Piece', 'Machine')
# user-wide
[System.Environment]::SetEnvironmentVariable('Best_Anime', $null, 'User')
# system-wide
[System.Environment]::SetEnvironmentVariable('Best_Anime', $null, 'Machine')
References
Cheers!