PoshCode Archive  Artifact [df5d1272c0]

Artifact df5d1272c0e1c7139eed7d00f717c172a417a363ad33c7e5f3835506c888f2ef:

  • File Set-WebConfig.ps1 — part of check-in [958c25595e] at 2018-06-10 13:52:57 on branch trunk — A function to set a sql connection string in a web.config file (user: unknown size: 1362)

# 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
# license: CC0
# function: Set-WebConfigSqlConnectionString
# x-poshcode-id: 528
# x-derived-from-id: 532
# x-archived: 2010-04-12T15:52:07
#
#
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}
	
	
	$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)
	
	}