PowerShell for Windows Admins

Feb 13 2012   12:16PM GMT

String replacement



Posted by: Richard Siddaway
Tags:
PowerShell

A question of the forum involved changing the file path for a folder. The original path was like this

$folder = "C:\FolderName\NextFolder\ThirdFolder"

 

The first attempt uses the –replace operator

PS> $newfolder = $folder -replace "C:\FolderName\", "D:\"
Invalid regular expression pattern: C:\FolderName\.
At line:1 char:30
+ $newfolder = $folder -replace <<<<  "C:\FolderName\", "D:\"
    + CategoryInfo          : InvalidOperation: (C:\FolderName\:String) [], RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression

 

The way to get round this is to escape the \ with another \ to keep the regular expressions happy

PS> $newfolder = $folder -replace "C:\\FolderName\\", "D:\"
PS> $newfolder
D:\NextFolder\ThirdFolder

 

Alternatively if you don’t care about happy regex then use the Replace() method of the string class

PS> $newfolder = $folder.Replace("C:\FolderName\", "D:\")
PS> $newfolder
D:\NextFolder\ThirdFolder

 

Its simpler than dealing with regex and escaping characters to meet its quirks

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: