2

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 ?

ggk
  • 117
  • 2
  • 9

1 Answers1

3

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):

mklement0
  • 382,024
  • 64
  • 607
  • 775