0

I am looking for a method in PowerShell to source the environment variables from running a .bat file script into the Env: provider.

Is there an equivalent to twa_env.cmd that will setup the environment for TWS correctly in PowerShell?

I can start a cmd.exe shell, CALL twa_env.cmd, then start PowerShell. That seems to work. What I cannot yet do is to start a PowerShell shell, run twa_env.cmd, and bring the new variable settings back into the PowerShell Env:.

7
  • Yeah: & tws_env.bat. Environment variables will be created in the powershell session. Commented Sep 21, 2018 at 14:45
  • @TheIncorrigible1 - That would be really nice. In your experience, does it work? Start a PowerShell console, run & tws_env.bat, then run conman or composer. Is that working for you? Commented Sep 21, 2018 at 15:30
  • I don't have it installed at the moment, but execute the batch script in a powershell session and run Get-Command -Name co* Commented Sep 21, 2018 at 15:34
  • 2
    Are you asking about stackoverflow.com/questions/42711294/…? Commented Sep 21, 2018 at 22:00
  • 1
    Does this answer your question? How can I source variables from a .bat file into a PowerShell script? Commented Apr 21, 2022 at 16:20

1 Answer 1

2

PowerShell can run a cmd.exe shell script (batch file), but it (naturally) has to execute it using cmd.exe. The problem is that when the cmd.exe executable closes, the environment variables it sets don't propagate to the calling PowerShell session.

The workaround is to "capture" the environment variables set in the cmd.exe session and manually propagate them to PowerShell after the batch file finishes. The following Invoke-CmdScript PowerShell function can do that for you:

# Invokes a Cmd.exe shell script and updates the environment.
function Invoke-CmdScript {
  param(
    [String] $scriptName
  )
  $cmdLine = """$scriptName"" $args & set"
  & $Env:SystemRoot\system32\cmd.exe /c $cmdLine |
    Select-String '^([^=]*)=(.*)$' |
    ForEach-Object {
      $varName = $_.Matches[0].Groups[1].Value
      $varValue = $_.Matches[0].Groups[2].Value
      Set-Item Env:$varName $varValue
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This does work. It was not working for me because the application -REQUIRES- administrator privs. I do not see why that would be needed, but I did not write the app. It also works with the Invoke-Expression I used. I will give you the check for this copy of the other answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.