Replace special character in powershell

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

  • Author
    Posts
  • #12950
    Profile photo of Akash Kumar
    Akash Kumar
    Participant

    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.

    Thanks
    Akash.

  • #12951
    Profile photo of Akash Kumar
    Akash Kumar
    Participant

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

  • #12953
    Profile photo of Bob McCoy
    Bob McCoy
    Participant

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

    The backslash is an escape character in Regex.

  • #12959
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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.