INI file parsing in PowerShell

前端 未结 7 1183
[愿得一人]
[愿得一人] 2020-11-27 05:16

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 (         


        
7条回答
  •  攒了一身酷
    2020-11-27 06:01

    This is really an extension to the current answer (couldn't seem to append a comment).

    I messed around with this to do rudimentary handling of integers and decimals...

    function Parse-IniFile ($file)
    {
      $ini = @{}
      switch -regex -file $file
      {
        #Section.
        "^\[(.+)\]$"
        {
          $section = $matches[1].Trim()
          $ini[$section] = @{}
          continue
        }
        #Int.
        "^\s*([^#].+?)\s*=\s*(\d+)\s*$"
        {
          $name,$value = $matches[1..2]
          $ini[$section][$name] = [int]$value
          continue
        }
        #Decimal.
        "^\s*([^#].+?)\s*=\s*(\d+\.\d+)\s*$"
        {
          $name,$value = $matches[1..2]
          $ini[$section][$name] = [decimal]$value
          continue
        }
        #Everything else.
        "^\s*([^#].+?)\s*=\s*(.*)"
        {
          $name,$value = $matches[1..2]
          $ini[$section][$name] = $value.Trim()
        }
      }
      $ini
    }
    

提交回复
热议问题