Created
May 27, 2026 23:02
-
-
Save JeffJacobson/cbee11232f898f8c7ec8dafb47aba240 to your computer and use it in GitHub Desktop.
Import environment variables from .env files using PowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .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