PowerShell Parse String and Search for Value

Parse a PowerShell string is something that may need to be done when handling a report or log file.

Looking around the net on how to parse a PowerShell string, there’s a lot of commands out there using “Select-String” or “-split” on a variable. This is good for separating the words or values of a string, but not much else. Further functionality is required to search those strings and determine further action.

For Example, a log file could contain the info below:

We want our script to always return the Host-IP, which might always be unique

The script to parse a string is below. While it is meant to be an example of how a string can be parsed, numbered, and called, it allows you to search for a value in the string. You’re also able to return a value AFTER the one you searched, which will be key in the example above.

To map out the steps of the script, after the user enters values, the following steps are taken:

  1. Remove line breaks, tabs, and most extra spaces from the string.
  2. Trim spaces from beginning and end of string.
  3. Split the string by ‘ ‘
    1. This creates a new array
  4. Loop through the array and add the values to a second array, which also counts the values.
  5. Loop through the second array, seeing if any value matches the “search” which the user provided.
  6. If value is found, calculate the actual value to return. 0 = the searched term. 1= the next value in the array, 2 = the second value after the searched term, etc.
  7. Return the value.

In our example, to test the functionality we can paste the string when prompted:Powershell Parse String

Then enter a value to search, in this case “Host-IP:” – including the colon:Enter search value for string

Enter the value you want to return, relative to “Host-IP”, which is the next value (1) “192.168.1.1”
Parsed string is searched and value returned.

Instead of inputting a value manually, this script could be modified to import a file instead. I would be open to expanding the script to do so by request.

Leave a Reply

Your email address will not be published.