Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

POWERSHELL: USE PARAMETERS AND CONFIGURATION FROM INI FILE, USE AS SPLATTING

June 22, 2017 09:14PM

I was working on one of my friends requirement for automating scripts, He wanted a safe way to use parameters and configuration values from external file instead of modifying actual script, I tried with CSV as well as cliXML file. but found INI file is simple format as external plain text file to parse information from. Its very easy for any non-technical person to edit and review it. Before starting I would like to show the content of the INI file (schema). Same configuration I will be using in next Powershell splatting examples.

Text starting with ; semicolon are the comments and only for information purpose (description) and will be skipped while processing (This line is not necessary to mentioned in the file but it is best practice to document everything), next block is the configuration Name, enclosed with square brackets [], this is a main part I will be using to find related block for Syntax and parameter joined with equal = sign. In below file I have 3 parameter blocks for Service, Process and Folder as shown.

POWERSHELL CREATE HASHTABLE FROM MICROSOFT EXCEL

INI file anotomy containing configuration data with closed brackets and configuration joined with equal sign and forward slash

Here is my code, parses this INI file and use Syntex parameters / value out of it. for example once I run the function Get-IniConfiguration -File C:\temp\Configuration.ini -Conf Service, It extract service block and convert it to hashtable in as same as variable name mentioned in -Conf parameter. for example my configuration.ini file contains Service block (as exactly same variable name $service will be created), Once it detects the correct block It creates hashtable with Service name variable. 

Next is using the Powershell splatting - "PowerShell Spatting is Bundling parameters before sending them along to a command can save your time", Simply using $Service as Get-Service @Service. It will take Name and ComputerName as syntax, parameter and value will be LanManServer and Localhost respectively. (This is the normal oneliner command I use Get-Service -Name LanManServer -ComputerName LocalHost), There are less chances for errors.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
function Get-IniConfiguration {
    ##############################
    #.SYNOPSIS
    #Convert INI data information to Hashtable for splatting
    #
    #.DESCRIPTION
    #The Get-IniConfiguration cmdlet fetch information from .ini file, and convert it to hashtable, This Hastable can be used later further as splatting. This is best for non technical users, and don't want to make any changes to script.
    #
    #.PARAMETER File
    #This is a File path. Extension can be .txt, .ini, .info or any other readable ascii file is supported, Below is the example content of file related to service.
    #[service]
    #Name=LanManServer
    #ComputerName=Localhost
    #
    #.PARAMETER Conf
    #This is a paramenter block mentioned in brackets, and same name variable created for splatting ie
    #[service] 
    #
    #.EXAMPLE
    #Get-IniConfiguration -File C:\temp\configuration.ini -Conf Service
    #Get-Service @Service
    #
    #Information is stored under $service (same name as -conf variable)
    #
    #.NOTES
    #http://vcloud-lab.com
    #Written using powershell version 5
    #Script code version 1.0
    ###############################
    
    [CmdletBinding()]
	param(
	    [Parameter(Position=0, Mandatory=$true)]
        [ValidateScript({
            If (Test-Path $_) {
                $true
            }
            else{
                "Invalid path given: $_"
            }
        })]
        [System.String]$File = 'C:\Temp\Test.ini',
		[Parameter(Position=1, Mandatory=$true)]
		[System.String]$Conf 
    )    
    $inifile = Get-Content -Path $File #-Raw -split '`r`n'
    $LineCounts = $iniFile.Count
    $ConfLineNumber = $iniFile | Select-String -Pattern "\[$Conf\]" | Select-Object -ExpandProperty LineNumber
    if ($ConfLineNumber -eq $null) {
        Write-Host "Please provide correct configuration name in -Conf parameter" -BackgroundColor DarkRed
        Break
    }
    $RawContext = $iniFile[$ConfLineNumber..$LineCounts] | Where-Object {$_.trim() -ne "" -and $_.trim() -notmatch "^;"}
    $FinalLineNumber = $RawContext | Select-String -Pattern "\[*\]" | Select-Object -First 1 -ExpandProperty LineNumber
    $FinalLineNumber = $FinalLineNumber - 1
    if ($FinalLineNumber -ge 1) {
        $FinalData = $RawContext | Select-Object -First $FinalLineNumber
        $FinalData = $FinalData | Where-Object {$_ -match "="}
    }
    else {
        $FinalData = $RawContext | Where-Object {$_ -match "="}
    }
    New-Variable -Scope Global -Name $Conf -Value ($FinalData | Out-String | ConvertFrom-StringData) -Force
}

Get-IniConfiguration -File .\Configuration.ini -Conf Service
Get-Service @Service

Another example I would like show about Folder, it does not recognize the single backward slash \ in the Path, so you will have to mention double backward slash. Also for switchparameter need to mention separately ie: Get-Childitem @Folder -Directory.

Powershell Parse INI file configuration, INI splatting, Ini data to hashtable.jpg

Splatting is very useful when you long and more than 2 Parameters to be selected, I frequently use them with external file (example as below for Send-MailMessage) so I don't have to touch my original script.

[MailMessage]
To=kunaludapi@vcloud-lab.com
From=noreply@vcloud-lab.com
Subject=This is test message
Body=Attached reports
Attachement=c:\\temp\\report.txt
SMTPServer=mail.vcloud-lab.com
Port=25

Download code from GitHub: https://github.com/kunaludapi/Powershell-INI-Parsing-as-spatting

Go Back

Comment