问题描述
我正在用 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
配置文件,变量就可用了.我已经尝试了点源(.filename.bat
)和调用(&filename.bat
)来自PowerShell的配置文件,这些都没有使变量可见.尝试使用 $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]
}
}}
我有这个代码,我确定它来自某个地方,但信用已经丢失,我想它来自 PowerInvoke-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 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!