Backup SharePoint web.config file with PowerShell

Just a quick post to share the technique I use to back up the web.config file of a web application. As you may know, the out of the box backup commands do not backup the web.config file for any web apps. Microsoft recommend that these are backed up separately, see

So unless ALL your web.config modifications are made via Central Admin, or the API (SPWebConfigModification) your web.config file changes or those made by third party applications or solutions are not captured during a backup and are not available for restore.

To work around this issue, I’ve extended the scripts I use to perform routine scheduled Web Application backups (via Backup-SPFarm) to include a file system copy of the web.config file. The following script should be self explanatory:

$webappName = “http://bc01”
$backupDir = “C:\backups”

Write-Host "Backing up $webappName web.config file…" -foreground Gray –nonewline

## Get the web application – by display name
$w = Get-SPWebApplication | where { $_.DisplayName -eq "$webappName"}

## Get the default (first) zone for the web app…
## You may wish to iterate through all the available zones
$zone = $w.AlternateUrls[0].UrlZone

## Get the collection of IIS settings for the zone
$iisSettings = $w.IisSettings[$zone]

## Get the path from the settings
$path = $iisSettings.Path.ToString() + "\web.config"

## copy the web.config file from the path
copy-item $path -destination $backupDir\$webappName

Write-Host "done" -foreground Green

I hope this helps…