在 Windows power shell 中,如何提取属性文件值并将其保存到环境变量中?

In Windows power shell, how do you extract a properties file value and save it to an env var?

我有一个包含如下条目的属性文件...

...
USERNAME=myuser
...

在我的 Makefile 中,我有以下使用类似 Unix 的命令来获取变量值的命令...

export USERNAME=$(shell grep USERNAME my_properties.txt | cut -d'=' -f 2-)

但是,在 Windows 能力 shell 中(也许命令提示符是正确的短语?),以上内容不起作用,因为“grep”不是标准命令(以及其他命令) .在 Windows power shell 环境中从属性文件中提取 属性 的等效方法是什么?

我们可以按照以下步骤在 PowerShell 中实现此目的

  1. 读取文件内容
  2. 将内容转换为键值对
  3. 创建具有所需值的环境变量

(如果您愿意,可以合并这些步骤,我将它们分开以便更好地理解)

这是脚本

$content = Get-Content .\user.properties -raw
$hashTable = ConvertFrom-StringData -StringData $content
$Env:USERNAME = $hashTable.USERNAME

假设cmd.exe是默认值shell:

export USERNAME=$(shell powershell -noprofile -c "(Select-String 'USERNAME=(.+)' my_properties.txt).Matches.Group[1]")

注意:-NoProfile 禁止加载 PowerShell 配置文件,不幸的是默认情况下会发生这种情况。如果您需要 -File 参数来执行 脚本文件 ,您可能还需要 -ExecutionPolicy Bypass,除非您的有效 execution policy 允许脚本执行。

以上使用 PowerShell CLI's -c (-Command) parameter to pass a command that uses the Select-String cmdlet,PowerShell 的 grep 模拟。


更接近于您的命令的是以下命令,它另外使用 -splitstring-splitting operator(仅显示原始 PowerShell 命令;将其放在上面的 "..." 中) :

((Select-String USERNAME my_properties.txt) -split '=', 2)[-1]