Skip to content

Instantly share code, notes, and snippets.

@Hectormalvarez
Last active April 23, 2024 22:46
Show Gist options
  • Save Hectormalvarez/89330da47be93f05beb2e6952b6f8a76 to your computer and use it in GitHub Desktop.
Save Hectormalvarez/89330da47be93f05beb2e6952b6f8a76 to your computer and use it in GitHub Desktop.
Set-EnvsFromEnvFile
function Set-EnvVarsFromDotEnv {
<#
.SYNOPSIS
Parses a .env file and sets environment variables from it.
.DESCRIPTION
This function reads a .env file, parses each line as a key-value
pair, and sets corresponding environment variables within the current
PowerShell session. The .env file format should have one key-value
pair per line, separated by an equals sign (=).
.EXAMPLE
Set-EnvVarsFromDotEnv -Path '.env'
This will read the .env file in the current directory and set the
environment variables defined within it.
.PARAMETER Path
The path to the .env file to be parsed. If not provided, defaults
to '.env' in the current directory.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false, Position=0)]
[string]$Path = '.env'
)
Get-Content -Path $Path | ForEach-Object {
$name, $value = $_ -split '=', 2
Set-Variable -Name $name -Value $value.Trim()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment