Search code examples
powershellmakefilewindows-10environment-variablesproperties-file

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


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?


Solution

  • 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]