Skip to content

Instantly share code, notes, and snippets.

@JeffJacobson
Created May 27, 2026 23:02
Show Gist options
  • Select an option

  • Save JeffJacobson/cbee11232f898f8c7ec8dafb47aba240 to your computer and use it in GitHub Desktop.

Select an option

Save JeffJacobson/cbee11232f898f8c7ec8dafb47aba240 to your computer and use it in GitHub Desktop.
Import environment variables from .env files using PowerShell
<#
.SYNOPSIS
Imports environment variables from .env files
.DESCRIPTION
Imports environment variables from .env files. '.env', then '.env.local'
.NOTES
Ordering for '.env.<not local> and '.env.*.local' is the default
order of Get-ChildItem.
#>
[CmdletBinding()]
param (
)
(
(
(
# Get all of the .env files
Get-ChildItem .env* |
# Sort so that '.local' files are after others.
Sort-Object {
[int]($_.Extension -ieq '.local')
} |
# Get the contents of each .env file
ForEach-Object {
Write-Host "Importing environment variables from $($_.Name)" -ForegroundColor Cyan
$_ | Get-Content
} |
# Convert output to string
Out-String
# Concatenate
) -join [System.Environment]::NewLine
) |
# Convert to hashtable
ConvertFrom-StringData
# Enumerate each key/value pair in the hash table
).GetEnumerator() |
ForEach-Object {
# Set the environment variable
Set-Item -Path "env:$($_.Name)" -Value $_.Value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment