String Replace Error in PowerShell

by gretty at 2013-04-30 22:36:35

Hello

In my PowerShell script I am getting an error that I dont understand.

The error is:
[quote] Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

Invalid regular expression pattern:
Menu "User" {
Button "EXDS" {
Walk_Right "EXDS"
}
}
.
At C:\test.ps1:7 char:18
+ ($output -replace <<<< $target) | Set-Content "usermenuTest2.4d.new"
+ CategoryInfo : InvalidOperation: (
Menu "User" {…do"
}
}
:String) , RuntimeException
+ FullyQualifiedErrorId : InvalidRegularExpression[/quote]

My script reads a file into a string (string A) then attempts to remove String A from another file. What does this error mean and how I can I fix it?

My code:
#set-executionpolicy Unrestricted -Force
#set-executionpolicy -scope LocalMachine -executionPolicy Unrestricted -force

$target=[IO.File]::ReadAllText(".\usermenuTest1.4d")
$output=[IO.File]::ReadAllText(".\usermenuTest2.4d")

($output -replace $target) | Set-Content "usermenuTest2.4d.new"
by mjolinor at 2013-05-01 03:24:48
That’s impossible to say exactly without knowing what’s in $Target. Regular expressions have their own syntax rules and set of reserved characters.

If you’re wanting to match what’s in $Target the regex metacharacters need to be escaped with backslashes in order to be interpreted literally. Fortunately the [regex] type has a static escape method you can use to do that for you:

$TargetRegex = [Regex]]

Then do your match opertation using $TargetRegex

($output -replace $TargetRegex) | Set-Content "usermenuTest2.4d.new"