Link to home
Start Free TrialLog in
Avatar of E=mc2
E=mc2Flag for Canada

asked on

Correct PowerShell Script to search and replace any text combination

I am using a script to search and replace text by drilling down into folders recursively and then replacing specific text.


The script is shown below.

The problem is that at times I get this type of error when changing the text it is searching for.



Select-String : The string C:\Users\Users1\AppData\Local\Programs\Program1 is not a valid regular expression: parsing "C:\Users\Users1\AppData\Local\Programs\Program1" 

- Unrecognized escape sequence \U.

At C:\Users\.....\Replace.ps1:3 char:126

+ ... ","*.vbs" | Select-String " C:\Users\Users1\AppData\Local\Prog...

+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: (:) [Select-String], ArgumentException

    + FullyQualifiedErrorId : InvalidRegex,Microsoft.PowerShell.Commands.SelectStringCommand




cls
$filePath = "C:\Users\Public\Documents\Documents1\Folder1"
  Get-Childitem -Path "C:\Users\Public\Documents\Documents1\Folder1" -Recurse -include "*.txt","*.ps1","*.bat","*.vbs" | Select-String "C:\Users\Users1\AppData\Local\Programs\Program1"
 Get-ChildItem $filePath -Recurse -include "*.txt","*.ps1","*.bat","*.vbs" | ForEach-Object {
# Read the file and use replace()
(Get-Content $_).Replace('C:\Users\Users1\AppData\Local\Programs\Program1','C:\Users\Public\Documents\Folder1\Programs1') | Set-Content $_
}

Open in new window


Any assistance is very much appreciated. 



ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial