Source/Import-DotEnv.ps1
|
<# .SYNOPSIS Loads environment variables from a .env file into the current PowerShell session. .DESCRIPTION Reads the specified .env file, converts it via ConvertFrom-DotEnv, and sets environment variables for the process scope. Warns if the .env file is not found. Throws if the file isn't well-formed. .PARAMETER Path The path to the .env file. If not specified, uses .env in the current directory. .EXAMPLE Import-DotEnv -Path ".env" .EXAMPLE ".env", ".env.local" | Import-DotEnv .INPUTS [System.String] The .env file path. Accepts pipeline input by value or by property name. .OUTPUTS None. #> function Import-DotEnv { [CmdletBinding(SupportsShouldProcess)] param( [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)] [string] $Path = ".env" ) process { if (-not (Test-Path -Path $Path)) { Write-Warning "$Path file not found." return } $values = ConvertFrom-DotEnv -Text (Get-Content -Path $Path -Raw) foreach ($name in $values.Keys) { if ($PSCmdlet.ShouldProcess($name, "Set environment variable from '$Path' (Process)")) { [Environment]::SetEnvironmentVariable($name, $values[$name], "Process") } } } } |