从文本文件中读取变量并将其设置为当前 PowerShell 会话环境变量

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

假设我有一个文本文件,它定义了一些像这样的变量

file : .env

USER=user
DB_NAME=userDB
DB_HOST=localhost
DB_PORT=5432

并且我希望 PowerShell 读取文本文件并将其导出到当前会话,因此当我有一个来自会话的 运行 程序并从 env 读取变量时,它将识别上面的变量,如何我在 PowerShell 中这样做吗?

使用 switch statement combined with the -split operator and use of Set-ItemEnv: 驱动器为当前进程设置环境变量:

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
    }
  }
}

注意:或者,您可以使用 Get-Content .env | ForEach-Object { ... } - 但是,由于技术原因,从 PowerShell 7.2.3 开始,这要慢得多(尽管在给定的用例中,这在实践中可能无关紧要):