Quantcast
Channel: /r/powershell – How to Code .NET
Viewing all articles
Browse latest Browse all 8793

Changing web.config files with Powershell

$
0
0

Hey guys,

I wrote a script to add an attribute to a web.config. It all works fine, and functions as expected, but this is going to be a mass change and it screws up the formatting of the web.config. I want to save the web.config and have it look exactly like I did before I added the value. Anyone have any experience with this? Below is my code.

$ComputerName = "TESTSERVER " #Backup existing Web.config file #Create Backup Directory if necessary and copy Invoke-Command -ComputerName $ComputerName -ScriptBlock{ $TimeStamp = Get-Date -Format "_yyyy_MM_dd_hh_mm_ss" $BackupFileName = "web.config_$TimeStamp" if (Test-Path "D:Backup") { Copy-Item -Path "D:TestAppWeb FilesTestAppweb.config" -Destination "D:Backup" - Force Rename-Item -Path "D:Backupweb.config" -NewName $BackupFileName -Force } else { New-Item -ItemType Directory "D:Backup" Copy-Item -Path "D:TestAppWeb FilesTestAppweb.config" -Destination "D:Backup" - Force Rename-Item -Path "D:Backupweb.config" -NewName $BackupFileName -Force } } $WebConfigContent = Invoke-Command -ComputerName $ComputerName - ScriptBlock{[xml](get-content "D:TestAppWeb FilesTestAppweb.config")} $root = $WebConfigContent.get_DocumentElement(); $ProtocolsPath = $root.'system.web'.webServices.protocols if($ProtocolsPath.remove) { $TestRemove = $true } else { $TestRemove = $false } #If Remove section exists, check if it is Documentation if ($TestRemove -eq $true) { foreach ($item in $ProtocolsPath.remove) { if ($item.name -eq "Documentation") { $TestDocumentation = $true } } } if ($TestRemove -eq $false) { $TestDocumentation = $false } if ($TestDocumentation -eq $true) { break } if ($TestDocumentation -eq $false) { $webConfigPath = "\$ComputerNamed$TestAppWeb FilesTestAppweb.config" $newEl=$WebConfigContent.CreateElement("remove"); $nameAtt1=$WebConfigContent.CreateAttribute("name"); $nameAtt1.psbase.value="Documentation"; $newEl.SetAttributeNode($nameAtt1); $WebConfigContent.configuration'system.web'.webServices["protocols"].AppendChild($newEl); $WebConfigContent.Save($webConfigPath) break } 

submitted by /u/theomegachrist
[link] [comments]

The post Changing web.config files with Powershell appeared first on How to Code .NET.


Viewing all articles
Browse latest Browse all 8793

Trending Articles