October 24th, 2012

PowerTip: Replacing a String Inside Another String with PowerShell

Doctor Scripto
Scripter

Summary: Learn two different techniques to replace strings inside another string by using Windows PowerShell.

Hey, Scripting Guy! Question I have the following string: this`”is a string. I want to remove the quotation mark (“) and replace it with nothing—no space, just nothing. I want the results to look like this: thisis a string. The backtick (`) is used to “escape” the quotation mark. How can I use the Replace method to replace the quotation mark with nothing, if the string is held in a variable $arr?

       Hey, Scripting Guy! Answer There are several approaches to this. Here are a couple of solutions:

  • Use the Replace method from the system.string .NET framework class.

$arr.Replace(“`””,””)

  • Use the ascii value of the quotation mark, and use the Replace method from the system.string .NET framework class.

$arr.Replace([char]34,””)

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.