TheToddmonster TheToddmonster - 4 months ago 14
PowerShell Question

Powershell - Update File Path in Multiple Batch Files

I found the following snippet of code and for one off string values and this works perfectly

$configFiles = Get-ChildItem . *.bat -rec
foreach ($file in $configFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object { $_ -replace "prodapp", "devapp" } |
Set-Content $file.PSPath
}


but when I go ahead and try to use the same code to update a file path, I get a regEx error

$configFiles = Get-ChildItem . *.bat -rec
foreach ($file in $configFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object { $_ -replace '\Program Files\App\AppClient\4.0', '\Program Files (x86)\App\AppClient' } |
Set-Content $file.PSPath
}


Error is

+ CategoryInfo : InvalidOperation: (\Program Files\App\
AppClient\4.0:String) [], RuntimeException
+ FullyQualifiedErrorId : InvalidRegularExpression


What am I missing? Thank you!

Answer

Backslashes and periods have special meanings in regular expressions. In your case you want to match against an actual backslash and period so you have to escape them with a backslash.

So your replace line should look like this:

Foreach-Object { $_ -replace '\\Program Files\\App\\AppClient\\4\.0', '\Program Files (x86)\App\AppClient' } |

To clarify, you only need to escape those types of characters in the first part of the replace statement (before the comma) as that is the regular expression. The second part of the replace statement (after the comma) is the text you want to replace it with and you don't have to escape those characters.