-
-
Save Mufaddal1125/4dd9ad67d6a1eb5f8f043e3ff62d7763 to your computer and use it in GitHub Desktop.
sets powershell environment variables from python-dotenv formatted .env file
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 | |
Exports environment variable from the .env file to the current process. | |
.Description | |
This function looks for .env file in the current directoty, if present | |
it loads the environment variable mentioned in the file to the current process. | |
based on https://github.com/rajivharris/Set-PsEnv | |
.Example | |
Set-PsEnv | |
.Example | |
# This is function is called by convention in PowerShell | |
# Auto exports the env variable at every prompt change | |
function prompt { | |
Set-PsEnv | |
} | |
#> | |
function Set-PsEnv { | |
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Low')] | |
param($localEnvFile = ".\.env") | |
#return if no env file | |
if (!( Test-Path $localEnvFile)) { | |
Throw "could not open $localEnvFile" | |
} | |
#read the local env file | |
$content = Get-Content $localEnvFile -ErrorAction Stop | |
Write-Verbose "Parsed .env file" | |
#load the content to environment | |
foreach ($line in $content) { | |
if ($line.StartsWith("#")) { continue }; | |
if ($line.Trim()) { | |
$line = $line.Replace("`"","") | |
$kvp = $line -split "=",2 | |
if ($PSCmdlet.ShouldProcess("$($kvp[0])", "set value $($kvp[1])")) { | |
[Environment]::SetEnvironmentVariable($kvp[0].Trim(), $kvp[1].Trim(), "Process") | Out-Null | |
} | |
} | |
} | |
} | |
Export-ModuleMember -Function @('Set-PsEnv') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment