Author Posts

June 28, 2013 at 3:54 pm

I am trying to import the content of an ini file structured as below:

[Services]
Print Spooler
Adobe Acrobat Update Service
Browser
[Backup]
BackupExec2010=No
BackupExec2012=No
WindowsBackup=Yes

I am using the regex "^\[(.+)\]" to find the headers but not sure how to split the rest of the file into useable sections. Any advice is appreciated.

June 29, 2013 at 10:18 am

Hmm. I'm not entirely sure a regex is completely the right approach. What you probably need to do is just go through the file line-by-line. When you see a line matching a header, your code would know what to do with the subsequent lines. Because INI file sections don't have a closing delimiter for a section, you can't easily grab just the contents of a section using a regex. I mean, each section but the last is "terminated" by the start of the following section... but I think you're going to work a lot harder that way.

For example, there's a C# class at http://www.codeproject.com/Articles/1966/An-INI-file-handling-class-using-C you might use as a procedural example. You'll notice that it uses some native-code DLLs from Windows to actually deal with the INI.

INI files are really a PITA, though. If you've got any control over how those are created, consider using something like XML instead. It's a lot easier to parse. INI is pretty 1980's tech.

June 29, 2013 at 2:15 pm

I didnt think of using an xml file for the ini part.I just want it to be easy to edit so that whoever uses the script can open the file and enter the services they want the script to monitor and backup software being used. What is the easiest way to build an xml configuration file?

June 29, 2013 at 2:33 pm

The easiest? Notepad.

Or write two scripts. Better yet, write them as functions, as put them in a module. The first is the one that reads the XML and does whatever. The second accepts input on parameters, and produces an XML file. E.g.,

New-MyXMLConfiguration -Services one,two,three,four -Backup whatever,you,want -FilePath MyConfig.xml

That way you have an easy way to produce the XML file, and an easy file format that the "main" tool can consume.

June 29, 2013 at 4:56 pm

Thanks for another fast response. I am trying to work through this now after finding out I should use [xml](gc $File) instead of import-clixml, it is going quite well. Thanks for the help Don I have both of your learn windows powershell books and they are fantastic. Do you plan to do any more soon?

June 29, 2013 at 5:16 pm

We'll probably do updates for v4 on the existing books early next year. It's a ton of work, and it doesn't pay much, so I can't afford to do many more than I do.

July 9, 2013 at 11:03 am

This may be more complicated than it's worth but YAML is a great format since it's machine readable like XML and easily human readable/editable. Great for config files.

Here's a YAML parser for Posh.

https://github.com/scottmuc/PowerYaml