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
?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With