PoshCode Archive  Artifact Content

Artifact e54d431a02e4fd1dd4f5724e4f9411c0fc851bdb333bfcbf0c76916756c613d0:

  • File Set-WebConfig.ps1 — part of check-in [1a80d9bd26] at 2018-06-10 13:53:57 on branch trunk — A function to set a sql connection string in a web.config file (user: Andy Schneider size: 1444)

# encoding: ascii
# api: powershell
# title: Set-WebConfig
# description: A function to set a sql connection string in a web.config file
# version: 0.1
# type: function
# author: Andy Schneider
# license: CC0
# function: Set-WebConfigSqlConnectionString
# x-poshcode-id: 536
# x-archived: 2012-12-29T04:38:46
# x-published: 2008-08-18T22:46:00
#
# Andy Schneider
# Get-PowerShell.com
#
function Set-WebConfigSqlConnectionString {
	param(  [switch]$help,
	        [string]$configfile = $(read-host "Please enter a web.config file to read"),
	        [string]$connectionString = $(read-host "Please enter a connection string"),
	        [switch]$backup = $TRUE	
		)
	
	$usage = "`$conString = `"Data Source=MyDBname;Initial Catalog=serverName;Integrated Security=True;User Instance=True`"`n"
	$usage += "`"Set-WebConfigSqlConnectionString -configfile `"C:\Inetpub\wwwroot\myapp\web.config`" -connectionString `$conString"
	if ($help) {Write-Host $usage;break}
	
	
	$webConfigPath = (Resolve-Path $configfile).Path 
	$backup = $webConfigPath + ".bak"

	# Get the content of the config file and cast it to XML and save a backup copy labeled .bak
	$xml = [xml](get-content $webConfigPath)

	#save a backup copy if requested
	if ($backup) {$xml.Save($backup)}

	$root = $xml.get_DocumentElement();
	$root.connectionStrings.add.connectionString = $connectionString
	# Save it
	$xml.Save($webConfigPath)
	
	}