Using the ‘Convertfrom-String’ command in PowerShell 5.0

Hello and Happy New year to you all.

My first post for the New Year is about the Convertfrom-String that is part of the PowerShell 5.0 release. I have to say that I found this command very useful recently and thought it a good idea to write about how to use it.

My sample log file looks like this:

I was looking for a way to load the whole log file into a manageable array using PowerShell. To start with I needed to see what would be my identifying value in each of my entries. As the ID element is unique and increments, I decided to use this. As you can see from the sample above there are varying fields including integers, dates, ranges, etc. All of these can be used in a manageable way.

To start, we need to create a template that we will use to define the elements we want to use.

As you can see from above I have literally just copied 2 parts from the log file. Now we can decided on which elements we want to be added to our array. As I said earlier, I am going to us the ID field as my unique field as the number increments in my log file. So I need to change the template to reflect this.

By changing the ID line (in both parts of the template) to:

Note that I have maintained the spacing of the first part “id = “, as this is what the script will look for in the log file.

The second part of the new template line is defining the type of variable by using [int] and the remaining part is identifying that this is the element I want to use as the identifier of each group id*:41986. We now need to wrap this is {} brackets – {[int]id*:41986}.

The next element I want to look at is the ‘received_time = 2015/12/22 23:58:26

As you can see this is a date format that we could use later if we need to compare dates, or work out duration, etc.

Similar to the ID element we define the variable type and put it in {} brackets

Note that we do not have to do this in both groups in the template.

For now I want to move on to the ‘docidrange = 31-40‘ as this is a range of values ranging from 31 to 40. For this I have broken the numbers up as follows:

As you can see I have created 2 new elements that the script will add to the array docidstart and docidend.  I have stated they are both integers and can be located in the log file by check for date range. The starting number for the range will be the docidstart number and the end number for the range will be the docidend number.

Now that we have a template with the elements we want to extract from our log file we now need to run the command, we do this with the following line

You can add or change any of the elements you want to use, just remember to keep the same formatting throughout the template.

Convertfrom-String certainly is a powerful command.

As always feel free to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *