Skip to content

Instantly share code, notes, and snippets.

@Mufaddal1125
Forked from grenzi/Set-PsEnv.psm1
Created December 29, 2021 06:11
Show Gist options
  • Save Mufaddal1125/4dd9ad67d6a1eb5f8f043e3ff62d7763 to your computer and use it in GitHub Desktop.
Save Mufaddal1125/4dd9ad67d6a1eb5f8f043e3ff62d7763 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