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("\", "\\")
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 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.
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.
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).
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] = @{}
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With