8

I have a batch file named bar.cmd with a single line: ECHO %Foo%.
How can I set Foo in a Powershell script so that when I call & .\bar.cmd, it will print Bar?

1 Answer 1

11

To set an environment variable in PowerShell:

Set-Item Env:foo "bar"

or

$env:foo = "bar"

If you want to do it the other way around:

When you run cmd.exe to execute a shell script (.bat or .cmd file) in PowerShell, the variable gets set in that running instance of cmd.exe but is lost when that cmd.exe instance terminates.

Workaround: Run the cmd.exe shell script and output any environment variables it sets, then set those variables in the current PowerShell session. Below is a short PowerShell function that can do this 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.

Comments

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.