如何将.bat文件中的变量源到PowerShell脚本中? [英] How can I source variables from a .bat file into a PowerShell script?

查看:154
本文介绍了如何将.bat文件中的变量源到PowerShell脚本中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用PowerShell替换.bat脚本的某些部分.批处理文件的配置是通过set适当环境变量的文件完成的.我正在寻找一种方法,可以将这些变量值加载到.ps1脚本中,而无需修改.bat文件(因为它们也在其他地方使用.

I'm replacing parts of a .bat script with PowerShell. Configuration for the batch files is done via files that set appropriate environment variables. I'm looking for a way to load those variable values into the .ps1 script, without modifying the .bat files (as they are also used in other places.

示例.bat如下所示:

set VAR_ONE=some_value
set VAR_TWO=/other-value

在批处理脚本中,我只需CALL配置文件,变量就可以使用了.我已经尝试了从PowerShell进行点源(. filename.bat)和调用(& filename.bat)配置文件,但都没有使变量可见.尝试同时使用$VAR_ONE$env:VAR_ONE语法访问它们.

In a batch script, I'd just CALL the configuration file and the variables would be available. I've tried both dot-sourcing (. filename.bat) and calling (& filename.bat) the configuration files from PowerShell, neither of those makes the variables visible. Tried accessing them with both with $VAR_ONE and $env:VAR_ONE syntax.

在不修改磁盘上格式的情况下加载此类配置文件的好方法是什么?

What would be a good way to load such configuration file without modifying it's format on disk?

推荐答案

我将解析它们(只是跳过所有不以set开头的行,并以第一个=字符进行拆分.可以做到这一点.从小型C#cmdlet或直接使用小型PowerShell脚本:

I'd parse them (just skip all lines that don't start with set and split them with first = character. You can do it from o small C# cmdlet or directly with a small PowerShell script:

CMD /c "batchFile.bat && set" | .{process{
    if ($_ -match '^([^=]+)=(.*)') {
        Set-Variable $matches[1] $matches[2]
    }
}}

我有这段代码,并且我确定它来自某个地方,但是功劳已经丢失了,我想它来自电源用于Invoke-Batch脚本的Shell社区扩展.

I have this code and I'm sure it comes from somewhere but credits have been lost, I suppose it comes from Power Shell Community Extensions for an Invoke-Batch script.

这篇关于如何将.bat文件中的变量源到PowerShell脚本中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆