'reads variable from a text file and set it to current PowerShell session env variable
let's say that I have a text file that defines some variables something like this
file : .env
USER=user
DB_NAME=userDB
DB_HOST=localhost
DB_PORT=5432
and I want PowerShell to read the text file and export it to current session so when I have a program that run from the session same and reads the variable from env it will recognize the variable above, how do i do that in PowerShell ?
Solution 1:[1]
Use a switch
statement combined with the -split
operator and use of Set-Item
with the Env:
drive to set environment variables for the current process:
switch -File .env {
default {
$name, $value = $_.Trim() -split '=', 2
if ($name -and $name[0] -ne '#') { # ignore blank and comment lines.
Set-Item "Env:$name" $value
}
}
}
Note: Alternatively, you could use Get-Content .env | ForEach-Object { ... }
- but, for technical reasons, that is significantly slower, as of PowerShell 7.2.3 (though, in a given use case, that may not matter in practice):
Get-Content
decorates each line read from its input file with ETS (Extended Type System) properties, which slows things down, even though these properties typically aren't needed.- GitHub issue #7537 asks for an opt-out to improve performance.
The
ForEach-Object
andWhere-Object
cmdlets are inefficiently implemented.- GitHub issue #10982 asks that this be fixed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |