Home > Blockchain >  reads variable from a text file and set it to current PowerShell session env variable
reads variable from a text file and set it to current PowerShell session env variable

Time:01-17

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 ?

CodePudding user response:

Use a switch statement and combined with the -split operator and use 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
    }
  }
}
  •  Tags:  
  • Related