【问题标题】:Read INI file parameters读取 INI 文件参数
【发布时间】:2016-02-23 21:22:30
【问题描述】:

我有一个具有以下配置的 INI 文件:

[Applications]
app1= aplication1
app2= aplication2

[BBDD]
server_bbdd = name_bbdd

[DATA]
data_dir = c:\data\

[LOGS]
data_log = c:\data\log\

我需要使用我的 PowerShell 脚本读取和加载应用程序数据。例如对于 app1,我需要将此应用的所有数据加载到数据库中(是 SQL-SERVER BBDD),然后对 app2 执行相同操作。

如何使用 PowerShell 读取和加载应用程序数据?

【问题讨论】:

  • 对于 app1,我需要将这个应用的所有数据加载到数据库中 什么“所有数据”?从哪里?进什么数据库?哪个表?解析 INI 文件很简单,但是您没有提供足够的信息让任何人猜测如何从那里继续。

标签: sql-server windows powershell scripting


【解决方案1】:

您可以像使用哈希一样使用 ini 文件,并创建一个哈希表并将它们放入变量中。 例如 $Applications = @{“app1”=”aplication1”;“app2”=”aplication2”}

这个 read-to-use 函数将读取 ini 文件并将这些部分分开,即节名和节值。 我们将它读取到内存中的哈希值,稍后您将需要它来输出。 “switch -regex”用于处理多个 if 语句。 -regex 将匹配子句(如果是字符串)视为 Regex(正则表达式,即 RegEx 字符:^ . [ ] - g G ? + * p P w W s S d D $)。

function Get-IniContent ($filePath)
    {
        $ini = @{}
        switch -regex -file $FilePath
        {
            "^\[(.+)\]" # Find Sections
            {
                $section = $matches[1]
                $ini[$section] = @{}
                $CommentCount = 0
            }
            "^(;.*)$" # Find Comments
            {
                $value = $matches[1]
                $CommentCount = $CommentCount + 1
                $name = "Comment" + $CommentCount
                $ini[$section][$name] = $value
            } 
            "(.+?)\s*=(.*)" # Find Keys
            {
                $name,$value = $matches[1..2]
                $ini[$section][$name] = $value
            }
        }
        return $ini
    }

之后,您可以将其读取到变量中,从而将这些变量输出到文件或其他东西中。

$iniContent = Get-IniContent “c:\temp\file.ini”
$iniContent[“Applications”]
$value = $iniContent[“Applications”][“app1”]
$iniContent[“Applications”].Keys | %{$iniContent["Applications"][$_]}
猜你喜欢
  • 2013-04-18
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-16
  • 2011-12-26
  • 2012-06-29
相关资源
最近更新 更多