Skip to content

Instantly share code, notes, and snippets.

@grenzi
Last active February 21, 2023 23:11
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save grenzi/82e6cb8215cc47879fdf3a8a4768ec09 to your computer and use it in GitHub Desktop.
Save grenzi/82e6cb8215cc47879fdf3a8a4768ec09 to your computer and use it in GitHub Desktop.
sets powershell environment variables from python-dotenv formatted .env file
<#
.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