Search code examples
xmlpowershellpowershell-2.0powershell-3.0powershell-4.0

How to replace the content of file containg backslash ( \ ) in its string using PowerShell?


I have a config file which has multiple placeholders which i want to replace with some other values using PowerShell but the below code it not able to replace the %WebClientPath%\www with value contained in $WebClientPath variable. It has this Path in it "C:\IWeb\Demo\Main\UIPresentation\WebApp" where as %VirtualApplicationName% gets replaced by the IMWeb

I tried removing \www from %WebClientPath% and it worked but i want \www also to be replaced. I think this is happening because of backslash ( \ )

[CmdletBinding()]
Param
(   
    [string]$PathofWebConfigFile="C:\Automate\Web.config"  ,
    [string]$VirtualApplicationName="IMWeb"  
)


# Code to get WebClient Path from PhysicalPath attribute.
$WebClientPath=(get-webapplication IMWeb).PhysicalPath


(Get-Content -Path "$PathofWebConfigFile") | ForEach-Object {$_ -Replace "%VirtualApplicationName%","$VirtualApplicationName"} | Set-Content -Path "$PathofWebConfigFile"
(Get-Content -Path "$PathofWebConfigFile") | ForEach-Object {$_ -Replace "%WebClientPath%\www","$WebClientPath"} | Set-Content -Path "$PathofWebConfigFile"

Solution


  • Slash \ is escaped by double slashes \\, try this:

    "mypath\www" -replace "\\www","\zzz"
    

    This cmdlet will replace \www with \zzz.