PowerShell for DBAs – Working with INI files
Posted by Rob Risetto on June 25, 2014
Over the last 3 years I have developed a range of major PowerShell scripts to deploy/configure Replication, SQL Server clustering onto multiple nodes and to perform Database Maintenance tasks (think Ola Hallengren SQL maintenance solution but in PowerShell).
Anyway all these major scripts required a large number of configuration parameters and as you would expect the passing of them via the command line wasn’t practical. I wasn’t a fan of XML configuration files, they are hard to read, easy to stuff, so I decided to work towards a traditional INI file solution, i.e. format of Parameter = <value> and one line per parameter.
Like all my PS projects I first performed a search on the inter web to see if someone else has solved the problem or had an example I could embellish, and I found the following gem to read in a INI file and generate a hash table of parameter/value pairs. Unfortunately I don’t have the original site where I copied the code snippet but kudos to the original author.
So here’s the Read INI function and the function call to read in a Config INI file.
Basically you get the contents of the Config file and pipe it into the ReadIniFile function, the function then creates a hash table and processes each line and stores the parameter name and value in the hash table. The resulting hash table is store in the $IniHashTable variable. The ReadINIFile function ignore lines prefixed with “;” or “[“, I typically use “;” to prefix comment lines in the INI file.
Ok so things you can do with parameter/value pairs in the hash table.
I can pass the hash table to other functions, in this example I want to validate the contents of the parameters. Note I don’t have to pass all parameters individually to the function.
The ValidateINI function header looks like below
I can iterate through all the parameter names and perhaps check that I have all parameters or any invalid parameter names.
I can retrieve a parameter value and use it in subsequent processing, in this example I’m retrieving the DB restore state value (eg. Recovery, NoRecovery or Standby) from the RestoreDBState parameter.
I can dynamically find the parameters with a particular name (in the example below the parameter name that ends with Period) and check that the corresponding parameter value has a correct value.
What I have found is that the ReadINIFile function and the ability to pluck out a parameter name and value has saved a heap of time when developing scripts with a large set of configuration parameters. It really has reduced the effort to validate, pass and work with configuration parameters.
In Part two of the series, I will show you how I used the ReadINIFile function to pass in a database excluded list and the Compare Array function to produce a final list of database names to process.
Code snippets are here PowerShell Code Snippets Part 1
Leave a Reply