How to Remove automatic web.config backup files in SharePoint using PowerShell

During SharePoint solution deployment, SharePoint takes a backup copy of the web.config with the name as web_.bak. Since SharePoint is taking the backup everytime when we deploy a solution during development of any webparts/any solution package, the files in the IIS physical folder will be keep on going, and its no longer required (in case of development/test).

I have created a small script in Powershell to delete the web.config backup files. Please note that this script is intended for development/test environment and dont directly use it in production environments. Also note that i am considering the default zone url of the web application. This script can be saved as .ps1 file (like RemoveSharePointWebconfigbackup.ps1) and can be schedule with windows scheduler to remove automatically, may be every day at 12AM.

Caution: Please Take the backup of IIS Folder before running at first time and second time

PowerShell Script :

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction “SilentlyContinue”
$WebApplication =”http://webapplicationurl”
$SPSite = New-Object Microsoft.SharePoint.SPSite($WebApplication)
$webApp = $SPSite.WebApplication
#get the IIS path
$IISSettings = $webApp.IisSettings[[Microsoft.SharePoint.Administration.SPUrlZone]::Default]

Write-Host ‘Displaying IIS path $IISSettings.Path’
$stIISPath = $IISSettings.Path.FullName
Write-Host $stIISPath
#write $WebApplication
$WebConfigBackFiles = Get-ChildItem $stIISPath web_*.bak
#Write-Host ‘ Files count =’
#Write-Host $WebConfigBackFiles
foreach ($tempFile in $WebConfigBackFiles)
 $t = “$stIISPath\$tempFile”
   #Write-Host $t
    Remove-Item $t