PowerShell 中的 INI 文件解析 [英] INI file parsing in PowerShell

查看:94
本文介绍了PowerShell 中的 INI 文件解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 PowerShell 中解析简单(无节)的 INI 文件.这是我想出的代码,有什么方法可以简化吗?

I'm parsing simple (no sections) INI file in PowerShell. Here code I've came up with, is there any way to simplify it?

convertfrom-stringdata -StringData ( `
  get-content .\deploy.ini `
  | foreach-object `
    -Begin { $total = "" }  `
    { $total += "`n" + $_.ToString() } `
    -End { $total } `
).Replace("\", "\\")

推荐答案

在互联网上搜索此主题后,我找到了一些解决方案.所有这些都是手动解析文件数据,所以我放弃了尝试制作标准 cmdlet 来完成这项工作的尝试.有一些奇特的解决方案,如this支持写作场景.

After searching internet on this topic I've found a handful of solutions. All of them are hand parsing of file data so I gave up trying to make standard cmdlets to do the job. There are fancy solutions as this which support writing scenario.

有更简单的,就我不需要编写支持而言,我选择了以下非常优雅的代码片段:

There are simpler ones and as far as I need no writing support I've chose following very elegant code snippet:

Function Parse-IniFile ($file) {
  $ini = @{}

  # Create a default section if none exist in the file. Like a java prop file.
  $section = "NO_SECTION"
  $ini[$section] = @{}

  switch -regex -file $file {
    "^\[(.+)\]$" {
      $section = $matches[1].Trim()
      $ini[$section] = @{}
    }
    "^\s*([^#].+?)\s*=\s*(.*)" {
      $name,$value = $matches[1..2]
      # skip comments that start with semicolon:
      if (!($name.StartsWith(";"))) {
        $ini[$section][$name] = $value.Trim()
      }
    }
  }
  $ini
}

这是 Jacques Barathon 的.

更新感谢 Aasmund Eldhuset 和 @msorens 的改进:空白修剪和评论支持.

Update Thanks to Aasmund Eldhuset and @msorens for enhancements: whitespace trimming and comment support.

更新 2 跳过任何 name=value 对,其中 name 以分号 ; 开头,它们是注释行.将 $ini [$section] = @{} 替换为 $ini[$section] = @{}.

Update 2 Skip any name=value pairs where name starts with a semicolon ; which are comment lines. Replaced $ini [$section] = @{} with $ini[$section] = @{}.

这篇关于PowerShell 中的 INI 文件解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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