Skip to content

Instantly share code, notes, and snippets.

@frabarz
Created February 11, 2020 19:06
Show Gist options
  • Save frabarz/037993331ef6b64270f0541ff718130e to your computer and use it in GitHub Desktop.
Save frabarz/037993331ef6b64270f0541ff718130e to your computer and use it in GitHub Desktop.
Loads the environment variables in a .env file (intended for bash) into the current terminal session.

For PowerShell on Windows 10.

By default this function attempts to locate a .env file in the current folder.
If the file is found, tries to load the environment variables set on it into the current terminal session.

Load-DotEnv

You can pass the path to any other file containing the variables you want to load as first argument.

Load-DotEnv ..\.env.production

If you want to automatically load the variables if a .env file exists after cding into a folder, you can put this command inside the prompt() function in your profile script.

The environment variables are expected to be written in format: export VARIABLE=value, where value can be surrounded by these quotation marks: ", ', and `.

function Load-DotEnv {
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Low')]
param(
[Parameter(Position = 0)]
[string]
$Path = ".\.env"
)
if (Test-Path $Path) {
$content = Get-Content $Path -ErrorAction Stop
foreach ($line in $content) {
if ($line.Trim() -match "^export (\w+)\=['`"]?(.+?)['`"]?;?$") {
$key = $matches[1]
$value = $matches[2]
if ($PSCmdlet.ShouldProcess("dotEnv: $($key)", "set value $($value)")) {
[Environment]::SetEnvironmentVariable($key, $value, "Process") | Out-Null
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment