# 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) }