Search code examples
powershellconfig

How can I update a changing value in Powershell in a web.config file?


I am trying to update text inside a web.config file with powershell, but I am having a very, very difficult time.

The problem is this line

<add key="Models.Catalog.Repository" value=Server23 />

You see where the Server23 is? this value sometimes can be empty, which will be represented as "" or sometimes it can have a different name like "\Server25\path"

How do I tell PowerShell to replace/insert data if the field is empty/has some text in it?

here is the full code

 $GP_AP= "Server1"
 $NewMD = "\\JohnWick"

    Invoke-Command -ComputerName $GP_AP  -ScriptBlock  {
    
    $date= Get-Date -Format "dd_MM_yyyy_HHMM_ss"
    $webfile = "C:\Program Files\TEST\IIS\Web.config"
    
    (Copy-Item -Path $webfile -Destination $webfile_Test_$Date)
    
    #[xml]$webconfigfile = Get-Content "C:\Program Files\TEST\IIS\Web.config"
    #[xml]$2 = Get-Content "\\Server1\C$\Program Files\TEST\IIS\Web.config"
    
    $olddata = "*"

    #(Get-Content $webfile -raw).Replace("<add key=`"Models.Catalog.Repository`" value=$olddata />","<add key=`"Models.Catalog.Repository`" value=$Using:NewMD />") `
     #| Set-Content "C:\Program Files\TEST\IIS\Web.config" -Force -Encoding UTF8 -ErrorAction Stop
    
    (Get-Content $webfile -raw).Replace('<add key="Models.Catalog.Repository" value=Server23 />',"<add key=`"Models.Catalog.Repository`" value=$Using:NewMD />") `
     | Set-Content "C:\Program Files\TEST\IIS\Web.config" -Force -Encoding UTF8 -ErrorAction Stop
 
    } # end of script block

Solution

  • $path        = '\\server\c$\Program Files\TEST\IIS\web.config'
    
    [xml]$config = Get-Content -Path $path -Raw
    
    $stuffIwant  = "\\Blah-244"
    
    $config.SelectNodes("//add[@key='Models.Catalog.Repository']") | `  
    ForEach-Object { $_.SetAttribute("value", $stuffIwant) }
    
    $config.Save($path)