Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting variables for batch files in Powershell

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?

like image 560
Arithmomaniac Avatar asked Mar 01 '17 15:03

Arithmomaniac


1 Answers

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
    }
}
like image 129
Bill_Stewart Avatar answered Oct 30 '22 09:10

Bill_Stewart