在Powershell中为批处理文件设置变量

8

我有一个批处理文件名为 bar.cmd,其中只有一行:ECHO %Foo%
当我调用& .\bar.cmd时,如何在PowerShell脚本中设置Foo,以便它打印Bar

1个回答

11

在PowerShell中设置环境变量:

Set-Item Env:foo "bar"
或者
$env:foo = "bar"

如果你希望采用另一种方式:

当你在PowerShell中运行cmd.exe以执行一个shell脚本(.bat.cmd文件)时,变量将在该运行实例的cmd.exe中设置,但在该cmd.exe实例终止时丢失。

解决方法:运行cmd.exe shell脚本并输出它设置的任何环境变量,然后在当前的PowerShell会话中设置这些变量。以下是一个可以为您执行此操作的简短PowerShell函数:

# 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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接