Replace special character in powershell

This topic contains 3 replies, has 3 voices, and was last updated by  Dave Wyatt 4 years, 4 months ago.

  • Author
  • #12950

    Akash Kumar

    Hi All,
    I am very new on powershell forum here. For one of my daily manually find and replace task i want to create a powershell script to find and replace some network location and replace with new one.
    Like :-
    To find : \\filedep\iservershare\DCSVWA
    Replace with \\EGSISFS01\VolksWagon\DCSVWA

    I am able to replace text without any special characters but for above I am getting regular expression error.
    And also after replacing above string i want to save result in a text file which logs records of files which have been updated.


  • #12951

    Akash Kumar

    I got the solution here:-
    $c = $c -replace [regex]::Escape('\\filedep\iservershare\DCSVWA'),('\\EGSISFS01\VolksWagon\DCSVWA')

  • #12953

    Bob McCoy

    $a = "\\filedep\iservershare\DCSVWA\somefilename.txt"
    $a = $a -replace "\\\\filedep\\iservershare\\DCSVWA","\\EGSISFS01\VolksWagon\DCSVWA"

    The backslash is an escape character in Regex.

  • #12959

    Dave Wyatt

    PowerShell's -replace operator uses regular expressions, and also works well on collections. If your $c variable happens to just be a single string (not a collection of strings), though, you can also just use the Replace() method of the String class, which keeps regex out of the picture:

    $c = $c.Replace('\\filedep\iservershare\DCSVWA', '\\EGSISFS01\VolksWagon\DCSVWA')

You must be logged in to reply to this topic.