Oliver Lipkau :- Get Ini File Contents in PowerShell

Background

In a previous post ended up hard coding database connectivity information in the the actual PowerShell code.

Not a good look.

Let us move that into an INI File.

Oliver Lipkau

BTW, here is the link to the previous post :

Db/2 – PowerShell – Lab Exercises – 01
Link

Oliver Lipkau

Ini File Management

PowerShell

Outline

  1. PowerShell
    • PowerShell Function File
      • Get-IniContent.ps1
    • Powershell PSM1
      • PSIni.psm1
    • Sample Invocation
      • readIniFile.ps1

PowerShell Function File

Get-IniContent.ps1
Set-StrictMode -Version Latest
Function Get-IniContent {

<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>&lt;#

<span id="mce_SELREST_end" style="overflow:hidden;line-height:0;"></span>$FileContent["Section"]["Key"]
        -----------
        Description
        Returns the key "Key" of the section "Section" from the C:\settings.ini file  

    .Link
        Out-IniFile
#&gt;  

    [CmdletBinding()]
    Param(
        [ValidateNotNullOrEmpty()]
        [ValidateScript({(Test-Path $_) -and ( ( (Get-Item $_).Extension -eq ".ini") -or ( (Get-Item $_).Extension -eq ".txt") ) })]
        [Parameter(ValueFromPipeline=$True,Mandatory=$True)]
        [string]$FilePath
    )  

    Begin
        {Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"}  

    Process
    {
        Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing file: $Filepath"  

        $ini = @{}
        switch -regex -file $FilePath
        {
            "^\[(.+)\]$" # Section
            {
                $section = $matches[1]
                $ini[$section] = @{}
                $CommentCount = 0
            }
            "^(;.*)$" # Comment
            {
                if (!($section))
                {
                    $section = "No-Section"
                    $ini[$section] = @{}
                }
                $value = $matches[1]
                $CommentCount = $CommentCount + 1
                $name = "Comment" + $CommentCount
                $ini[$section][$name] = $value
            }
            "(.+?)\s*=\s*(.*)" # Key
            {
                if (!($section))
                {
                    $section = "No-Section"
                    $ini[$section] = @{}
                }
                $name,$value = $matches[1..2]
                $ini[$section][$name] = $value
            }
        }
        Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing file: $FilePath"
        Return $ini
    }  

    End
        {Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
} 

PowerShell Application File

PSIni.psm1

$PsIniModuleHome = Split-Path -Path $MyInvocation.MyCommand.Path -Parent

# Name of the Section, in case the ini file had none
# Available in the scope of the module as `$script:NoSection`
$script:NoSection = "_"

# public functions
. "$PsIniModuleHome\Functions\Get-IniContent.ps1"

readIniFile.ps1

Set-StrictMode -Version Latest

###########################################################
# Import Module
###########################################################
Import-Module .\PSIni.psm1  -NoClobber -ErrorAction Stop

###########################################################
# Get Current Folder
###########################################################
$currentFolder=Convert-Path .

###########################################################
# Ini - Get Current File
###########################################################
$fileIni = "dbsettings.ini"

###########################################################
# Ini - Get Current File ( fullname)
###########################################################
$fileIniFullname = $currentFolder + [IO.Path]::DirectorySeparatorChar + $fileIni;

$fileContent = Get-IniContent ($fileIniFullname);

###########################################################
# Ini File - Read
###########################################################
$section="Database";

$key="server";
$dbServerHost = $fileContent[$section][$key]

$key="port";
$dbServerPort = $fileContent[$section][$key]

$key="database";
$dbDatabase = $fileContent[$section][$key]

$key="userid";
$dbUserID = $fileContent[$section][$key]

$key="password";
$dbUserPassword = $fileContent[$section][$key]

###########################################################
# Ini File - Display
###########################################################
"Database Server :- $dbServerHost"

"Database Server Port :- $dbServerPort"

"Database :- $dbDatabase"

"Database UserId :- $dbUserID"

"Database User Password :- $dbUserPassword"

Configuration Files

Outline

  1. Configuration Files
    • Ini File
      • dbsettings.ini

Configuration File

dbsettings.ini

[Database]
server=localhost
port=50000
database=WIDEWRLD
userid=db2user
password=simplepassword

Control Files

Outline

  1. Invoke
    • PowerShell
      • pass file name to Powershell file

Powershell

Invoke

powershell -file ./readIniFile.ps1
Output

invoke_2018104_0447PM

Dedicated

Dedicated to Oliver Lipkau :-

Work with INI files in PowerShell using hashtables
Link

One thought on “Oliver Lipkau :- Get Ini File Contents in PowerShell

  1. Hey, man.
    Cool that you found use for my module.

    I would just like to point out, that the part of the comment based help you removed from the function is lacking the beginning of the comment block (<#).
    Importing that file should fail

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s