Search code examples
powershellvariablesenvironment-variablesenvironment

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

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