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

Viewed 194

I have a properties file with entries like the below ...

...
USERNAME=myuser
...

In my Makefile, I have the below which uses Unix like commands to get the value of the variables ...

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

However, in a Windows power shell (maybe command prompt is the right phrase?), the above doesn't work because "grep" is not a standard command (among others). What's the equivalent way to extract a property from a properties file in a Windows power shell environment?

2 Answers

We could achieve this in PowerShell by following the below steps

  1. Read the contents of the file
  2. Convert the contents into key-value pairs
  3. Create environment variable with the required value

(you can combine the steps if you like, I've kept them separate for better understanding)

Here's the script

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

Assuming that cmd.exe is the default shell:

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

Note: -NoProfile suppresses loading of PowerShell's profiles, which unfortunately happens by default. Should you need the -File parameter to execute a script file, you may additionally need -ExecutionPolicy Bypass, unless your effective execution policy allows script execution.

The above uses the PowerShell CLI's -c (-Command) parameter to pass a command that uses the Select-String cmdlet, PowerShell's grep analog.


A closer analog to your command would be the following, which additionally uses -split, the string-splitting operator (showing the raw PowerShell command only; place it inside the "..." above):

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