PowerShell

PowerShell: Manipulate Strings (Bulk) in Text Files for further processing

Lately, I’ve prepared some PowerPoint slides for the scripting module of a course for ongoing system engineers. Now it’s time to share my work with the PowerShell community. The slides are about string manipulation. In this blog post we will deal with a text file of e-mail addresses. For furter processing, all content (domain names) of the right side of the @ are to be removed. The problem: The domain names are different.

So I decided to write a little script that does exactly what I need.

Starting point

Here is the text file with E-Mail addresses.

1

Now let’s move on manipulating the strings so that all domain names and @ will be removed and the output will be save in a new file.

The Code

Open PowerShell ISE. Copy the code below into your ISE session and change the path of the files in line 1 and 7.


$get=Get-Content C:\Temp\Mail.txt

foreach ($g in $get)
{
$index=$g.IndexOf('@')
$substring=$g.Substring(0,$index)
Add-Content C:\Temp\usernames.txt -Value $substring
}

The Result

After a few seconds the newly created output file will look like this:

Unbenannt.PNG

Mission accomplished.

Hope that this was good template for your string manipulation duty.

Keep in mind that IndexOf and Substring are your best friends when it comes to string manipulation.

I am looking forward to ideas and suggestions in the comments.

Categories: PowerShell

Tagged as: ,

2 replies »

  1. Hi Patrick
    Like all the time with Posh, there are different ways to reach the goal.
    For my part I’m more familiar with the following :

    $Names = foreach ($item in $data)
    {
    $item.split(“@”)[0]
    }
    Cutting the string with split method on @, then gather only first part ([0]). Here I feed a var called $Names, but we also can build a PSCustomObject in the foreach loop, to add some other values.
    I.e. :
    $Names = foreach ($item in $data)
    {
    [PSCustomObject]@{
    Name = $item.split(“@”)[0]
    Domain = $item.split(“@”)[1]
    }
    }
    … and let’s go with the var $Names to later treatments.

    Regards
    Olivier

    Liked by 1 person

Leave a Reply to Olivier Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.