如何将配置文件引入 Powershell 脚本? [英] How can I introduce a config file to Powershell scripts?
问题描述
假设我有一个名为 Foo.ps1 的 Powershell 脚本
Assume that I have a Powershell script called Foo.ps1
我想介绍一个名为 Foo.ps1.config 的 XML 配置文件
I would like to introduce an XML configuration file called Foo.ps1.config
我可以在其中指定我的环境设置,例如:
where I can specify my environment settings something like:
<FunctionsDirectory>
$ScriptDirectory\Functions
</FunctionsDirectory>
<ModulesDirectory>
$ScriptDirectory\Modules
</ModulesDirectory>
然后我想在 Foo.ps1 的开头加载这个配置,以便我可以将我的模块和点符号导入到 Functions 目录中.
And then I would like to load this configuration in the begining of Foo.ps1 so that I can import my modules and dot notate to the Functions directory.
如何在 Powershell 中实现此目的?
How can I achieve this in Powershell?
推荐答案
可能是一个更简单的解决方案....假设你的配置文件名为Confix.xml",试试这个:
Probably an easier solution.... Assuming your configuration file is names "Confix.xml", try this:
PS Testing> [xml]$configFile= get-content .\Config=.xml
PS Testing> $configFile
xml configuration
--- -------------
version="1.0" configuration
从新变量中读取数据:
PS Testing> $configFile.configuration.appsettings
#comment add
-------- ---
Vars {add, add}
PS Testing> $configFile.configuration.appsettings.add
key value
--- -----
var1 variableValue1
var2 variableValue2
PS Testing> $configFile.configuration.appsettings.add[0].value
variableValue2
长话短说:将变量转换为 XML,然后获取内容.
Long story short: Cast your variable as XML, and do a get-content.
在本例中,Config.xml 如下所示:
In this case, the Config.xml looks like this:
<?xml version="1.0"?>
<configuration>
<startup>
</startup>
<appSettings>
<!--Vars -->
<add key="var1" value="variableValue1"/>
<add key="var2" value="variableValue2"/>
</appSettings>
</configuration>
这篇关于如何将配置文件引入 Powershell 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!