Posted by: Richard Siddaway
when relevant content is
added and updated.
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:\"
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:\")
Its simpler than dealing with regex and escaping characters to meet its quirks