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

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.

How to run GPResult on a remote client with PowerShell

In the past, to run the GPResult command, you would need to either physically visit this client, have the user do it, or use and RDP connection.  In all cases, this will disrupt the user.  First, you need PowerShell remoting enabled on the target machine.  You can do this via Group Policy . Open PowerShell and type this command. Invoke-Command –ScriptBlock {GPResult /r} –ComputerName <ComputerName> Replace <ComputerName> with the name of the target.  Remember, the target needs to be online and accessible to you.

Error icon when creating a GPO Preference drive map

You may not have an error at all.  Take a look at the drive mapping below. The red triangle is what threw us off.  It is not an error.  It is simply a color representation of the Replace option of the Action field in the properties of the drive mappings. Create action This give you a green triangle. The Create action creates a new mapped drive for users. Replace Action The Replace action gives you a red triangle.  This action will delete and recreate mapped drives for users. The net result of the Replace action is to overwrite all existing settings associated with the mapped drive. If the drive mapping does not exist, then the Replace action creates a new drive mapping. Update Action The Update action will have a yellow triangle. Update will modify settings of an existing mapped drive for users. This action differs from Replace in that it only updates settings defined within the preference item. All other settings remain as configured on the mapped drive. If the