-
Notifications
You must be signed in to change notification settings - Fork 0
/
DotEnvLoad.ps1
30 lines (26 loc) · 1.02 KB
/
DotEnvLoad.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Adjusted for PS v2.0, based on https://stackoverflow.com/a/72001469
# This code is shared under CC BY-SA like the original answer (https://creativecommons.org/licenses/by-sa/4.0/)
param(
[string]$Path,
[switch]$Verbose,
[switch]$Remove,
[switch]$RemoveQuotes
)
try {
# $variables = Select-String -Path $Path -Pattern '^\s*[^\s=#]+=[^\s]+$' -Raw
$variables = Select-String -Path $Path -Pattern '^\s*[^\s=#]+=[^\s]+$'
} catch {
if ($Remove){} Else { Write-Output "Cannot open $Path; skipping... `n" }
}
foreach($var in $variables) {
$var = $var.Line
$keyVal = $var -split '=', 2
$key = $keyVal[0].Trim()
# $val = $RemoveQuotes ? $keyVal[1].Trim("'").Trim('"') : $keyVal[1]
$val = If ($RemoveQuotes) {$keyVal[1].Trim("'").Trim('"')} Else {$keyVal[1]}
# [Environment]::SetEnvironmentVariable($key, $Remove ? '' : $val)
[Environment]::SetEnvironmentVariable($key, $(If ($Remove) {''} Else {$val}))
if ($Verbose) {
"$key=$([Environment]::GetEnvironmentVariable($key))"
}
}