Use PowerShell to Replace Text in Strings

Use PowerShell to Replace Text in Strings

  • Comments 20
  • Likes

Summary: The Scripting Wife learns how to use Windows PowerShell and regular expressions to replace text in strings.

Microsoft Scripting Guy, Ed Wilson, here. I just finished a meeting with the Microsoft TechEd people about doing a series of five Live Meetings next week (beginning on March 28) about Windows PowerShell for the Road to TechEd. It will be a way cool Scripting Week, and sign up is already going on. The series will run Monday through Friday (five sessions), and they are called PowerShell: Learn It Now Before It’s an Emergency. The sessions will be live at 8:00 (Pacific Standard Time -8 GMT).

It is going to be WAY cool, and the Scripting Wife will be there also. You can find all five of my live meetings on the TechEd 2011 online. Sign up for all five because they will be interactive with lots of demos and lots of questions. We are even going to be streaming it on the Learn PowerShell page of the Script Center, and you will be able to ask questions via Twitter. I will be filtering for the #ScriptingWeek hash tag.

When the TechEd people asked me about doing a Road to TechEd Live Meeting, I said I would like to do an entire week, but only if I could schedule it prior to the 2011 Scripting Games. They were great to work with, and they were flexible with my scheduling. Therefore, we now have a week of Live Meetings for a last minute work out to get you into top shape for the games.

Speaking of learning Windows PowerShell and getting ready for the 2011 Scripting Games, I wonder what the Scripting Wife is up to.

“Yoo hoo, Scripting Wife,” I said with a rather loud voice.

I waited for a seemingly long time, with my ears straining for the slightest sound.

“Hmm…where did she go?” I said to myself. “Where are you, my dear?”

Without warning, she was standing in the doorway of my home office. I do not know how she does that. At times, it seems that she floats silently through the house.

“Did you bellow?” she asked mockingly.

“I am not certain ‘bellow’ is the correct word—perhaps ‘discretely inquire’ would be better,” I suggested.

“I am not your blog that you can edit. I said bellow,” she stated matter-of-factly.

“Well then…I ‘bellowed.’ You need to learn some more regular expressions if you expect to compete in this year’s Windows PowerShell Scripting Games,” I said.

“Instruct me, oh my magnificent fount of scripting knowledge,” I imagined her saying.

“Show me, Script Monkey,” she actually said.

“OK, I will slide over and let you drive. Open the Windows PowerShell prompt and type ‘dollar a equals this is a string,’” I said.

“Not that old thing. I have something better to type,” she said.

The following code is what she typed (<space> is one tap of the Space bar, <enter> is the Enter or Return key):

$a<space>=<space> “Script Monkeys have a tendency to be boring!”<enter>
$a<enter>

The result of that command is shown here:

Image of command output

“You think you are pretty smart,” I deadpanned.

“I am indeed,” she said with a laugh.

“OK, if you want to find out if the word Script is in the string stored in $a, what would you do?” I asked.

“I would use the Match operator,” she said triumphantly.

“Show me,” I said.

Without a second’s hesitation, she typed the following.

$a<space>-match<space>”Script”<enter>

The actual command and its associated output are shown here:

PS C:\> $a -match "Script"

True

“That will work. Now, I am going to teach you another special character—it is the dollar sign. It is like the opposite of the caret character that I showed you yesterday in that it means the match has to occur at the end of the string,” I said. “I want you to match the word boring at the end of the string.”

The Scripting Wife thought for a second, and typed the following command:

$a<space>-match<space>"boring!$"<enter>

“Excellent. You avoided a trap that I set for you by including the exclamation point in your match. Now remove the exclamation point and see what happens,” I suggested.

She immediately recalled her previous command, and removed the exclamation point. Here is her command and the associated output:

PS C:\> $a -match "boring$"

False

“Let me see how you are doing,” I asked.

She scooted over a bit, and I looked at her Windows PowerShell console, which is shown in the following image:

Image of command output

“Now that we know that we can match words in a string in different positions, let’s make some modifications to the string. To do this, we will use the Replace operator. The Replace operator works just like the Match operator. The syntax is input string, operator, match pattern, replacement string. Let me draw it for you,” I said.

I picked up a piece of paper, and drew the following table.

Input string

Replace operator

Match pattern

Replacement string

$a

-replace

"boring!$"

"exciting!"

“The cool thing is that the syntax is just like the Match operator, except that you add the replacement string to it. This is really helpful because I always use the Match operator to test my match pattern prior to using the Replace operator,” I said.

“I got it already. Let me show you,” she said impatiently.

The Scripting Wife typed for only a few seconds. She used the Up arrow to recall her previous command, and changed Match to Replace. She then used the End key to go to the end of the command and added the word exciting to the command. Here is her command:

$a -replace "boring!$", "exciting!"

The command and its associated output are shown here:

PS C:\> $a -replace "boring!$", "exciting!"

Script Monkeys have a tendency to be exciting!

PS C:\>

“Now check the string that is stored in the $a variable,” I said.

She pressed three keys and said, “It is still the same.”

“Therefore, if you want to actually replace text in the variable, you need to assign it to the variable by using the equals sign. Go ahead and make that change, and show me your work,” I said.

She thought for a few seconds, and then used the Up arrow to retrieve her command. Here is the command that she created:

$a = $a -replace "boring!$", "exciting!"

The following image shows all the commands she used today.

Image of command output

“OK, exciting, Script Monkey. I have had all the fun I can stand. I will see you later,” she said as she headed for the door.

“Wait, what about lunch?” I asked.

“There are some bananas on the kitchen counter downstairs. I also picked up a coconut while I was at the store. You can fix that too,” she said. “See ya later.”

And with that, she was gone.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Once you use the replace command the data shown is only a reflection of what it will look like. If I go back and see what the variable actually is the data just resorts back to the original text. Do you have to save the variable?

  • Nevermind I just saw what went wrong. I forgot to use $a = before my command.

  • @Steve yes you have to save it back.

  • Is there any way to tell if the replace actually happened without comparing the result with the original string?  It would be nice if $Matches or $0 were set, but they don't appear to be.  Are there any other automatic variables set on a replace?  I've even tried using a [regex] object and hoping something is set in that object, but I could not find anything.

  • Is there a way to use variables in the -replace option (e.g.

    $a = "I want to be doing something else."

    $b = "anything"

    $a = $a -replace "something" $b

    This gives an error in PS. Can it be done in some way?

  • Doug,

    You are missing the comma in the last statement.  It should read:

    $a = $a -replace "something", $b

    Regards.

  • This is great, just what I was looking for for a script pack I'm working on for Exchange 2010 cross-forest migrations with preflight validation goodness.

    One problem though, I'm using an INI file to define global variables (reading in data from the INI into globals works fine).

    I end up with two string variables, lets call them $email_domain and $anchor_domain.  If the users address is in $user_address and I want to replace the user domain with the anchor domain, I then run this:

    $anchor_address = $user_address.replace($email_domain,$anchor_domain)

    Problem is it doesn't seem to work, it's like it isn't finding the $email_domain string value.  If I replace it with a literal it works fine.  Ideas?  Do I need to cast it or something?

  • @Keith

    $anchor_address=$user_address -replace $email_domain,$anchor_domain)

    social.technet.microsoft.com/.../threads

  • "“Yoo hoo, Scripting Wife,” I said with a rather loud voice.

    I waited for a seemingly long time, with my ears straining for the slightest sound.

    “Hmm…where did she go?” I said to myself. “Where are you, my dear?”

    Without warning, she was standing in the doorway of my home office. I do not know how she does that. At times, it seems that she floats silently through the house.

    “Did you bellow?” she asked mockingly.

    “I am not certain ‘bellow’ is the correct word—perhaps ‘discretely inquire’ would be better,” I suggested.

    “I am not your blog that you can edit. I said bellow,” she stated matter-of-factly.

    “Well then…I ‘bellowed.’ You need to learn some more regular expressions if you expect to compete in this year’s Windows PowerShell Scripting Games,” I said.

    “Instruct me, oh my magnificent fount of scripting knowledge,” I imagined her saying.

    “Show me, Script Monkey,” she actually said."

    What's all that about!?!? No relevance whatsoever. Not even funny.

  • @Dan r.e. "What's all that about!?!? No relevance whatsoever. Not even funny."

    Lighten up, Francis.

    I found the article informative; I appreciate the authors efforts.

    Whether funny or just a bit silly the dialogue was effective at explaining some subtle points.

    @Scott:

    r.e. telling if replace actually replaced anything without comparing old/new strings

    Yeah, I wish PowerShell could do that.

    Looks like Perl got that one right.  I am finding this to be a very helpful overview btw:

       www.johndcook.com/regex.html

  • Test if a replacement occurred:

    if( ($s -replace 'b','c') -ne $s){'string replaced'}else{'not replaced'}

  • Great story man!

  • The  replace character replaces all the occurence of the match at once. Is there any way to restrict it to the first match.

    ex $a= "How are you? How was the match"

    $a= $a -replace "how" ,  "Who"

    running this  gives me this

    Who are you? Who was the match

  • PS > "How are you? How was the match" -replace ' How',' When'

    How are you? When was the match

  • Scripting Guy is always like that. Its a bit salt-in-wound reading about his holidays all over the place and whatnot but he does ultimately deliver. You just learn to scroll to the good bit.

    Or you know..you can go read some nice dry MSDN + .Net Framework articles. Those have *lots* of signal..