How can I source variables from a .bat file into a PowerShell script?
If you are using the PowerShell Community Extensions, it has a Invoke-BatchFile
that does this. I use with the Visual Studio vcvarsall.bat file to configure my PowerShell session to use the Visual Studio tools.
I'd parse them (just skip all lines that don't start with set
and split them with first =
character. You can do it from o small C# cmdlet or directly with a small PowerShell script:
CMD /c "batchFile.bat && set" | .{process{ if ($_ -match '^([^=]+)=(.*)') { Set-Variable $matches[1] $matches[2] }}}
I have this code and I'm sure it comes from somewhere but credits have been lost, I suppose it comes from Power Shell Community Extensions for an Invoke-Batch
script.
The preferred option would be to change the configuration to a .ps1
file and change the variable definitions to PowerShell syntax:
$VAR_ONE = 'some_value'$VAR_TWO = '/other-value'
Then you'll be able to dot-source the file:
. filename.ps1
If you want to stick with the format you currently have, you'll have to parse the values, e.g. like this:
Select-String '^set ([^=]*)=(.*)' .\filename.bat | ForEach-Object { Set-Variable $_.Matches.Groups[1].Value $_.Matches.Groups[2].Value}
Note: The above won't work in PowerShell versions prior to v3. A v2-compatible version would look like this:
Select-String '^set ([^=]*)=(.*)' .\filename.bat | ForEach-Object { $_.Matches} | ForEach-Object { Set-Variable $_.Groups[1].Value $_.Groups[2].Value}