forked from rajbos/home-automation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimport-env.ps1
39 lines (35 loc) · 1.64 KB
/
import-env.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
31
32
33
34
35
36
37
38
39
# Inspired by https://stackoverflow.com/a/76723749
function Import-Env {
[CmdletBinding(SupportsShouldProcess)]
[Alias('dotenv')]
param(
[ValidateNotNullOrEmpty()]
[String] $Path = '.env',
# Determines whether variables are environment variables or normal
[ValidateSet('Environment', 'Regular')]
[String] $Type = 'Environment'
)
$Env = Get-Content -raw $Path | ConvertFrom-StringData
$Env.GetEnumerator() | Foreach-Object {
$Name, $Value = $_.Name, $_.Value
# Account for quote rules in Bash
$StartQuote = [Regex]::Match($Value, "^('|`")")
$EndQuote = [Regex]::Match($Value, "('|`")$")
if ($StartQuote.Success -and -not $EndQuote.Success) {
throw [System.IO.InvalidDataException] "Missing terminating quote $($StartQuote.Value) in '$Name': $Value"
} elseif (-not $StartQuote.Success -and $EndQuote.Success) {
throw [System.IO.InvalidDataException] "Missing starting quote $($EndQuote.Value) in '$Name': $Value"
} elseif ($StartQuote.Value -ne $EndQuote.Value) {
throw [System.IO.InvalidDataException] "Mismatched quotes in '$Name': $Value"
} elseif ($StartQuote.Success -and $EndQuote.Success) {
$Value = $Value -replace "^('|`")" -replace "('|`")$" # Trim quotes
}
if ($PSCmdlet.ShouldProcess($Name, "Importing $Type Variable")) {
switch ($Type) {
'Environment' { Set-Content -Path "env:\$Name" -Value $Value }
'Regular' { Set-Variable -Name $Name -Value $Value -Scope Script }
}
}
}
}
Import-Env