Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INI file parsing in PowerShell

Tags:

powershell

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("\", "\\")
like image 920
Artem Tikhomirov Avatar asked Jan 06 '09 19:01

Artem Tikhomirov


People also ask

How do I read a PowerShell script config file?

After loading c:\app. config, we are displaying path of currently loaded configuration file, using CurrentDomain. GetData() method. By following the above steps, we can load and read a custom config file in current app domain within PowerShell script.

How do I view a .INI file?

How to Open and Edit INI Files. It's not a common practice for people to open or edit INI files, but they can be opened and changed with any text editor. Just double-clicking it will automatically open it in the Notepad application in Windows.

What is INI parser?

Introduction. iniParser is a simple C library offering ini file parsing services. The library is pretty small (less than 1500 lines of C) and robust, and does not depend on any other external library to compile. It is written in ANSI C and should compile on most platforms without difficulty.

How do I structure an INI file?

The INI file consists of sections and keys. The name of a section in the *. ini file is always entered inside the square brackets. Each section contains several keys (the key must be always assigned to the section that begins in the file before this key).


1 Answers

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
}

This one is Jacques Barathon's.

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

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

like image 139
Artem Tikhomirov Avatar answered Oct 01 '22 23:10

Artem Tikhomirov