Uderc programming article aggregator sites

Trim title off of string using the replace command

Advertisement
Below is a simple task to read in data from a text file to use in account creation.
Get-Content employee.txt |
ForEach{
    $ID = ($_ -split ';')[0]
    $fname = ($_ -split ';')[1]
    $lname = ($_ -split ';')[2]
A problem that has came up which I did not anticipate was titles.  Titles such as MBA etc. throw off the creation of the account. I have a title like this myself an understand why someone is proud to append it to the last of their name because
they worked very hard to get it.  In this case I need to trim it off to create the account. Below is an example of a data file
1234;test;user, MBA;
4567;test;user2 MBA;
8901;test;user3;
Thought this would be an easy fix and here is how I attempted to correct it below
$lname = $string
$string -replace ",*" -replace " "
$string
My thought was a comma or a space could be used to divide the last name the same as I divided the individual fields in the text file with a semicolon. Is there an easy method to do this? The replace seems easy enough but the problem is I'm not familiar with
the syntax in powershell.
Advertisement
The best answer: RegEx is an excellent tool but itt tkes a programmers mind to understand its subtleties.  It is a good excercize in declaritive thinking and in recursive parsing systems.  Once understood the lesson is transferrrable.
I do not recomment it to new scripters.  After you gains some mastery of a scripting system then RegEx becomes nmuch easier to understand.  I am not a RegEx wizard although I have used it since before it had a name.  It was part of all editors
before we had PCs.  VI and HPs EDIT,  MsEDIT and others.  EDLIN uses a primitive form of RegEx from the minicomputer era.  Of course EDLIN is no more.
¯\_(ツ)_/¯
I wouldn't necessarily call myself a new scripter, been doing it a few months now and whilst there is definitely a lot more i could learn, i find that when i need to accomplish something i figure it out eventually, it's how i learn best! It does leave me short
of tips and tricks you'd find in the early chapters of a book though!