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

Sticky Key problem between Windows Server 2012 and LogMeIn

This week I instructed my first class using Windows Server 2012 accessed via LogMeIn and discovered a Sticky Key problem every time you press the Shift key. Here is my solution to resolve this.  First off, in the Preferences of LogMeIn for the connection to the Windows Server, click General . Change the Keyboard and mouse priority to Host side user and click Apply at the bottom. On the Windows 2012 server, open the Control Panel – Ease of Access – Change how your keyboard works . Uncheck Turn on Sticky Keys . Click Set up Sticky Keys . Uncheck Turn on Sticky Keys when SHIFT is pressed five times . Click OK twice. If you are using Windows Server 2012 as a Hyper-V host, you will need to redo the Easy of Use settings on each guest operating system in order to avoid the Sticky Key Problem. Updated Information: March 20, 2013 If you continue to have problems, Uncheck Turn on Filter Keys .

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.

Where did a User’s Account Get Locked Out?

Updated: May 15, 2015 When this article was originally published, two extra carriage returns were add causing the code to malfunction.  The code below is correct.   My client for this week’s PowerShell class had a really interesting question. They needed to know where an account is being locked out at. OK, interesting. Apparently users hop around clients and forget to log off, leading to eventual lock out of their accounts. The accounts can be unlocked, but are then relocked after Active Directory replication. This problem is solved in two parts. The first one is to modify the event auditing on the network. The second part is resolved with PowerShell. The first part involves creating a group policy that will encompass your Domain Controllers. In this GPO, make these changes. Expand Computer Configuration \ Policies \ Windows Settings \ Security Settings \ Advanced Audit Policy Configuration \ Audit Policies \ Account Management Double click User Account Management C...