从文本文件中读取变量并将其设置为当前 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-Item
和 Env:
驱动器为当前进程设置环境变量:
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 开始,这要慢得多(尽管在给定的用例中,这在实践中可能无关紧要):
Get-Content
用 ETS (Extended Type System) 属性修饰从其输入文件读取的每一行,这会减慢速度,即使这些属性 通常 不需要。
- GitHub issue #7537 要求选择退出 以提高性能。
ForEach-Object
and Where-Object
cmdlet 实施效率低下。
- GitHub issue #10982 要求修复此问题。
假设我有一个文本文件,它定义了一些像这样的变量
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-Item
和 Env:
驱动器为当前进程设置环境变量:
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 开始,这要慢得多(尽管在给定的用例中,这在实践中可能无关紧要):
Get-Content
用 ETS (Extended Type System) 属性修饰从其输入文件读取的每一行,这会减慢速度,即使这些属性 通常 不需要。- GitHub issue #7537 要求选择退出 以提高性能。
ForEach-Object
andWhere-Object
cmdlet 实施效率低下。- GitHub issue #10982 要求修复此问题。