如何将配置文件引入Powershell脚本? [英] How can I introduce a config file to Powershell scripts?

查看:141
本文介绍了如何将配置文件引入Powershell脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为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屋!

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