PS C:\>

Unleash your script

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework.

Use MahApps.metro built-in dialogs

Apply beautiful modal dialog into your project.

How to apply a theme on your GUI?

Some tips on how to apply a theme on your GUI ...

Showing posts with label INI. Show all posts
Showing posts with label INI. Show all posts

Wednesday, 25 May 2016

How to work with INI file using powershell



Hello,

In my previous post "How to parse an INI file in powershell", I explained how to parse an Ini file and extract its content. In this article, I’ll show you how to exploit the output of this function.
A quick reminder:

The function parseInifFile receives an *ini file as input and returns an array. The array contains two columns which looks like this:

Section                        Content
-------                           -------
[owner]                       {name,organization}
[database]                   {server,port,file}


The first column contains all Sections of the Ini file (type: String). And the second column contains the pair key/value (type: Hashtable).

With this little introduction, let's go to the next step:

You can wether use your own ini file or take the file "my_INI_FILE.ini" available here.
Open powershell and browse to the directory containing the file. Copy the content of common.ps1 and execute it so that we can use the function parseIniFile, or execute the function parseIniFile in your current PS session. Then enter the following command line:

Now you should have something like this:








First of all, you need to identify what are you looking for in your INI file, then you can proceed. I selected some scenarios that may be useful to you in the second part of this article.

Basic manipulation:

If you want to access a value manually with nothing special in mind; this is how it’s done:

Select the hashtable $myIniContent  and redirect the output; that way we can access to the property Section and/or Content like it’s shown below:












In powershell v4.0, you can access it directly by doing
$my_INI_Content.Section if you want all sections
$my_INI_Content.Content if you want all contents

You can access a specific Section and its Content by specifying his index between brackets. Note that the index start form 0 not 1; so count carefully J . For instance, if you want to access the second line you need to type 1, not 2. 
Here is an example:
I want to access the first line of  $my_INI_Content, I just need to type $my_INI_Content[0].


Now, you know the entire trick to exploit the output of the function.

Going further:

That’s it for the easy task. But what if we want to go further? 
Here begins the difficult part:

Case 1:

       Let's suppose that a specific section exists (but you don’t know its index) and you want to access its content:
Create the variable $SectionToFind to specify which section you're looking for like below.


As you can see in the picture, to access key/value content, you just need to type $TargetSection.Content .


Case 2:

Let’s do something even more complicated. In our INI file, we know that the key “server” exists, and we want to find to which section it belongs and what is its value.

So we want something like this:
  - Key entered: "server" -
The section is : [database]
The value is : 192.168.2.62

How do we achieve that?

Well, it's not really an easy task. I even spent a lot of time on it.

But before that, here is the first approach for people who don't need the section in their output (I understand that you may want to save many lines of code):



It works also with duplicated key in your ini file (at the condition that it’s not duplicated inside the same Section).


However, if you want the value of Section, you need to insert an intermediate value inside the pipeline. So it becomes something like this:


And that gives you this output:




I wrapped all of those scripts inside a tool that list all sections and content (keys/values) if you are interested. Here is a preview of the tool:


You can download it here.

That’s all folks!
Thanks for reading !
Share:

Saturday, 21 May 2016

How to Parse an INI file in Powershell




Hello,

I think that all of us reading this article already know what an Ini file is. Though there may be many uses to those kinds of files, they are kind of hard to deal with when we want to access a value. I started to write this script to see if we can parse an ini file and solve, even if by little, the problem.

The problem with .ini files compared with xml file is that there are no tags to access elements.

Here’s an example of INI file content:

; last modified 1 April 2001 by John Doe
[owner]
name=John Doe
organization=Acme Widgets Inc.

[database]
; use IP address in case network name resolution is not working
server=192.0.2.62    
port=143
file="payroll.dat"

Which lines are considered as commented lines?

Lines which begin with “;” are considered as commented lines
$COMMENT_CHARACTERS = ";"

Which lines are considered as a Section header?

A section structure is always something like: [mySection01]
So, It may contains Capital letter, number and specials characters. These are the specials characters supported by this script: _ %<>/#+- , blank space is also supported. In my script, this is done by specifying a regex chains:
$HEADER_REGEX = "\[+[A-Z0-9._  %<>/#+-]+\]"

So what do we have in the Script?


  • First Step:

Useful lines are selected and set in a PScustomObject

$CONTENT_USEFUL = $ContentFile | Where { ($_ -notmatch "^\s*$COMMENT_CHARACTERS") -or ($_ -notmatch "^$COMMENT_CHARACTERS") }
$ALL_SECTION_HASHTABLE = $CONTENT_USEFUL | Where { $_ -match $HEADER_REGEX  } | % { [PSCustomObject]@{ Section= $_ ; Index = [Array]::IndexOf($CONTENT_USEFUL,$_) }}

  • Second Step

Each lines that doesn’t match the header section’s regex are stored in $SECTION_STRING and then processed

We take the index of the next section and subtract it with the current section to get the content between those two sections. However, there are cases when there is nothing between two sections (I already took that into account in the script so don’t worry).

$SECTION_STRING = $CONTENT_USEFUL | Select-Object -Index  (($SECTION_INI[$i-1].Index+1)..($SECTION_INI[$i].Index-1)) | Out-String
$CONVERTED_OBJ = convertfrom-stringdata -stringdata $SECTION_STRING

The magic function here is convertfrom-stringdata -stringdata
It really made my day. 

Here is a little example of the capabilities of this function:

$myString"
server=192.0.2.62     
port=143
file='payroll.dat'
"
ConvertFrom-StringData -StringData $myString 


Here is the output




As we can see, this function converts a string that contains one or more key and value pairs into a hashtable.

  • Last step

We put all of those elements into a big Array. :) 
The result looks like this:

Section:                                              Content:
----------                                               -------------
[owner]                                               {name,organization}
[database]                                          {server,port,file}



Here is the complete script:





Share:

Popular Posts

Join us on Facebook

STATS

Contact Form

Name

Email *

Message *

image
Hello,

Thank you for visiting my blog and reading this far.

I'm mainly focusing on scripting, software development and modern workpalce experiences with Microsoft Technology. I created this blog for the main purpose of sharing my knowledge. Hope you will appreciate my works and will help you in yours. You are friendly invited to leave any kind of feedback in the comment sections of my posts.

Please note that all posts on this blog are my own opinions and are provided "as is", without warranty of any kind.