简体   繁体   English

如何将配置文件引入 Powershell 脚本?

[英]How can I introduce a config file to Powershell scripts?

Assume that I have a Powershell script called Foo.ps1假设我有一个名为 Foo.ps1 的 Powershell 脚本

I would like to introduce an XML configuration file called Foo.ps1.config我想介绍一个名为 Foo.ps1.config 的 XML 配置文件

where I can specify my environment settings something like:我可以在其中指定我的环境设置,例如:

<FunctionsDirectory>
     $ScriptDirectory\Functions
</FunctionsDirectory>
<ModulesDirectory>
     $ScriptDirectory\Modules
</ModulesDirectory>

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.然后我想在 Foo.ps1 的开头加载这个配置,以便我可以将我的模块和点符号导入到 Functions 目录中。

How can I achieve this in Powershell?如何在 Powershell 中实现这一目标?

Probably an easier solution.... Assuming your configuration file is names "Confix.xml", try this:可能是一个更简单的解决方案......假设你的配置文件名为“Confix.xml”,试试这个:

PS Testing> [xml]$configFile= get-content .\Config=.xml
PS Testing> $configFile
xml                                  configuration
---                                  -------------
version="1.0"                        configuration

Reading data out of your new variable:从新变量中读取数据:

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

Long story short: Cast your variable as XML, and do a get-content.长话短说:将您的变量转换为 XML,然后执行获取内容。

In this case, the Config.xml looks like this:在这种情况下,Config.xml 如下所示:

<?xml version="1.0"?>
<configuration>
  <startup>
  </startup>
  <appSettings>
    <!--Vars -->
    <add key="var1" value="variableValue1"/>
    <add key="var2" value="variableValue2"/>
  </appSettings>
</configuration>

For an alternative to XML configuration, if you are flexible to use other type of configuration.对于 XML 配置的替代方案,如果您可以灵活地使用其他类型的配置。 I suggest using a global PS configuration file and here is how:我建议使用全局 PS 配置文件,方法如下:

Create a Powershell configuration file ( Eg Config.ps1 ), then put all configuration as global variable and init it as a first step so that configuration values should be available in your script context.创建一个 Powershell 配置文件(例如 Config.ps1 ),然后将所有配置作为全局变量并将其初始化为第一步,以便配置值应该在您的脚本上下文中可用。

Benefit of this approach is that various type of data structure such as scalar variable, collections and hashes can be used in Config.ps1 PS file and referenced easily in the PS code.这种方法的好处是可以在 Config.ps1 PS 文件中使用各种类型的数据结构,例如标量变量、集合和哈希,并在 PS 代码中轻松引用。

the following is an example in action:下面是一个正在运行的例子:

在此处输入图片说明

Here is the C:\\Config\\Config.ps1 file:这是 C:\\Config\\Config.ps1 文件:

$global:config = @{   
    Var1 = "Value1"

    varCollection = @{       
        item0     = "colValue0"
        item1   = "colValue1"
        item2  = "colValue2"
    }       
}

Then load the functions/variables from Config.ps1 file in this module C:\\Module\\PSModule.psm1, like so:然后从 C:\\Module\\PSModule.psm1 模块中的 Config.ps1 文件中加载函数/变量,如下所示:

$scriptFiles = Get-ChildItem "$PSScriptRoot\Config\*.ps1" -Recurse

foreach ($script in $scriptFiles)
{
    try
    {       
        . $script.FullName 
    }
    catch [System.Exception]
    {
        throw
    }
}

Lastly, initialization script contains this one line below: ( C:\\Init.ps1 ).最后,初始化脚本包含下面这一行:( C:\\Init.ps1 )。

Import-Module $PSScriptRoot\\Module\\PSModule.psm1 -Force

After running the Init.ps1.运行Init.ps1后。 global:config variable will be available in your script context. global:config 变量将在您的脚本上下文中可用。 Here is the output:这是输出:
在此处输入图片说明

Based on Keith's solution ... Code to load XML:基于Keith 的解决方案......加载 XML 的代码:

   $configFile = "c:\Path2Config"
    if(Test-Path $configFile) {
        Try {
            #Load config appsettings
            $global:appSettings = @{}
            $config = [xml](get-content $configFile)
            foreach ($addNode in $config.configuration.appsettings.add) {
                if ($addNode.Value.Contains(‘,’)) {
                    # Array case
                    $value = $addNode.Value.Split(‘,’)
                        for ($i = 0; $i -lt $value.length; $i++) { 
                            $value[$i] = $value[$i].Trim() 
                        }
                }
                else {
                    # Scalar case
                    $value = $addNode.Value
                }
            $global:appSettings[$addNode.Key] = $value
            }
        }
        Catch [system.exception]{
        }
    }

To populate variables from the XML values:从 XML 值填充变量:

            $variable1 = $appSettings["var1"]
            $variable2 = $appSettings["var2"]

And the associated XML:以及相关的 XML:

<?xml version="1.0"?>
<configuration>
  <startup>
  </startup>
  <appSettings>
<!--Vars -->
    <add key="var1" value="variableValue1"/>
    <add key="var2" value="variableValue2"/>
  </appSettings>
</configuration>

Another solution (similar to @yantaq's) is just have a separate script and load that.另一个解决方案(类似于@yantaq 的)只是有一个单独的脚本并加载它。

So config.ps1 contains:所以config.ps1包含:

$Environment = $Environment.ToUpper()
$GDriveUNC = "\\servername.domain.net\Data"
$BinLocation = "$pwd\bin-$Environment"

Note that in this case $Environment is an argument to the main script, and you can do any manipulation you want.请注意,在这种情况下, $Environment是主脚本的参数,您可以进行任何您想要的操作。

Then in main script, just run this 'config' script, like so:然后在主脚本中,运行这个 'config' 脚本,像这样:

. $PSScriptRoot\config.ps1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM