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:.
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
}
}