PowerShell for Windows Admins

Feb 13 2012   12:16PM GMT

String replacement

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


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

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

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.

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:

Share this item with your network: