Skip to main content

Utilizing PowerShell’s String Manipulation

The System.String object in PowerShell is a very useful object to get to know.  Many times I see Network Admins trying to create a lot of extra code that is not necessary when it comes to manipulating the contents of a string.  Even though I instruct that outputting data as a string is not a good PowerShell process, we need to be able to handle string data as input.  A case in point, what if you need to extract data from the message portion of an event log entry?  To simulate a string with multiple lines, I use this code:
$String = "This is a set of data.`n"
$String += "It has multiple lines.`n"
$String += "I need to extract the name of a computer.`n"
$String += "Computer Name: Indy-DC1.`n"
$String += "Now, try to extract it."
You can see that the string is telling us our objective.  I want to extract the name of the computer, Indy-DC1, from this string. The `n provides for a carriage return.  This is what the string looks like when you ask for the variable $String:
PS C:\> $String
This is a set of data.
It has multiple lines.
I need to extract the name of a computer.
Computer Name: Indy-DC1.
Now, try to extract it.
First let’s explore a couple of methods.  If you execute the command $String | Get-Member, you will see a list of the methods that are available to you.
To get a description of the methods for the object System.String, we can go to MSDN.  Take a look at the MSDN article for System.String. Since only one line of the string actually has the name of the computer, we need to somehow eliminate all the other lines.  Take a look at the Split method.  According to MSDN:
Returns a string array that contains the substrings in this string that are delimited by elements of a specified Unicode character array. Parameters specify the maximum number of substrings to return and whether to return empty array elements.
So we are going to turn this string into an array.  We need to use a delimiter to separate each line.  The easiest way to do this is by using the carriage return.
$String = $String.Split("`n")
The Split method has split up the string.  There are two ways to find the container of the array that holds the computer name.  If the string data is always on the same line, we could use the index number.  Remember, the first container of the array is at index 0.
$Data = $String[3]
If we do not know what line the value is on, we can utilize other information in the line that does not change to search for it.
ForEach ($Item in $String)
{
    If ($Item.Contains("Computer Name:"))
    {
        $Data = $Item
    }

}

This code cycles through each line of the string in the array.  It utilizes the Contains method of System.String.  If the string contains the text that follows (Computer Name:), the response is TRUE.  If it is TRUE, then that line of text is saved in the variable $Data.
If we take a look at $Data, this is what we get.
PS C:\> $Data
Computer Name: Indy-DC1.
We are getting close, but we are not down to just the computer name.  Utilizing the Replace method allows us to remove text from the string that we do not want.
$Data = $Item.Replace("Computer Name:", "")
Now the output looks like this.
PS C:\> $Data
 Indy-DC1.
We still have a period at the end of the string and a space at the beginning.  To deal with the period, let’s use the Replace method again.
$Data = $Item.Replace("Computer Name:", "").Replace(".","")
We then add our second Replace method to handle the period.  Now for the extra space.  We could use Replace, but the string method also has a Trim.  Trim will remove all spaces to the left and right of the string.  TrimStrart and TrimEnd will remove just the spaces to the left and right of the string.
$Data = $Item.Replace("Computer Name:", "").Replace(".","").Trim()
I used Trim to ensure there were not any spaces after the text that I could not see.  Here is the final output.
PS C:\> $Data
Indy-DC1
Take the time to look at the member information for each object that you use in PowerShell.  You never know, someone may have already written the code that you need.  Below is the final code for used in this post.
$String = "This is a set of data.`n"
$String += "It has multiple lines.`n"
$String += "I need to extract the name of a computer.`n"
$String += "Computer Name: Indy-DC1.`n"
$String += "Now, try to extract it."

$String = $String.Split("`n")


ForEach ($Item in $String)
{
    If ($Item.Contains("Computer Name:"))
    {
        $Data = $Item.Replace("Computer Name:", "").Replace(".","").Trim()
    }

}

Comments

Popular posts from this blog

Adding a Comment to a GPO with PowerShell

As I'm writing this article, I'm also writing a customization for a PowerShell course I'm teaching next week in Phoenix.  This customization deals with Group Policy and PowerShell.  For those of you who attend my classes may already know this, but I sit their and try to ask the questions to myself that others may ask as I present the material.  I finished up my customization a few hours ago and then I realized that I did not add in how to put a comment on a GPO.  This is a feature that many Group Policy Administrators may not be aware of. This past summer I attended a presentation at TechEd on Group Policy.  One organization in the crowd had over 5,000 Group Policies.  In an environment like that, the comment section can be priceless.  I always like to write in the comment section why I created the policy so I know its purpose next week after I've completed 50 other tasks and can't remember what I did 5 minutes ago. In the Group Policy module for PowerShell V3, th

Return duplicate values from a collection with PowerShell

If you have a collection of objects and you want to remove any duplicate items, it is fairly simple. # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   # Remove the duplicate values. $Set1 | Select-Object -Unique 1 2 3 4 5 6 7 What if you want only the duplicate values and nothing else? # Create a collection with duplicate values $Set1 = 1 , 1 , 2 , 2 , 3 , 4 , 5 , 6 , 7 , 1 , 2   #Create a second collection with duplicate values removed. $Set2 = $Set1 | Select-Object -Unique   # Return only the duplicate values. ( Compare-Object -ReferenceObject $Set2 -DifferenceObject $Set1 ) . InputObject | Select-Object – Unique 1 2 This works with objects as well as numbers.  The first command creates a collection with 2 duplicates of both 1 and 2.   The second command creates another collection with the duplicates filtered out.  The Compare-Object cmdlet will first find items that are diffe

How to list all the AD LDS instances on a server

AD LDS allows you to provide directory services to applications that are free of the confines of Active Directory.  To list all the AD LDS instances on a server, follow this procedure: Log into the server in question Open a command prompt. Type dsdbutil and press Enter Type List Instances and press Enter . You will receive a list of the instance name, both the LDAP and SSL port numbers, the location of the database, and its status.