Powershell – Cannot commit configuration changes because the file has changed on disk

asp.netiispowershell

I would like to have a powershell script that could create an IIS web site.
but I am getting error

New-IISSite : Filename:
\?\C:\Windows\system32\inetsrv\config\applicationHost.config Error:
Cannot commit configuration changes because the file has changed on
disk At C:\projects\salonsecretSrc\RegisterWebSite.ps1:38 char:9
+ New-IISSite -BindingInformation $strIssBindigFormat -Name $st …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-IISSite], FileLoadException
+ FullyQualifiedErrorId : System.IO.FileLoadException,Microsoft.IIS.Powershell.Commands.NewIISSiteComman

this is my script:

$strCurrentPath = $MyInvocation.MyCommand.Path
$strWebSiteFolder = Get-ChildItem (dir $strCurrentPath)
$strWebSiteBindingPath = $strWebSiteFolder.Directory.FullName+"\build\WebSite"
$strCurrentFolderName = $strWebSiteFolder.Directory.Name
$strIssSiteName = "$strCurrentFolderName.local"
$strIssBindigFormat = ":80:$strIssSiteName"

Write-Host "Current Script path: $strCurrentPath"
Write-Host "IIS Web Site phycical path: $strWebSiteBindingPath"
Write-Host "IIS SiteName: $strIssSiteName"
Write-Host "IIS Bindindg Format: $strIssBindigFormat"
Write-Host "Creating App Pool - $strIssSiteName"
        New-WebAppPool -Name $strIssSiteName -Force
        Write-Host "Creating Web Site Pool - $strIssSiteName"
        New-IISSite -BindingInformation $strIssBindigFormat -Name $strIssSiteName -PhysicalPath "$strWebSiteBindingPath" -Force
        Write-Host "Mapping Pull and Web Site - $strIssSiteName"
        Set-ItemProperty "IIS:\Sites\$strIssSiteName" -name applicationPool -value $strIssSiteName
        Write-Host "$strIssSiteName WebSite Created"

what could be an issue how to solve ?

it could create an web site first time but second time if I remove it manually it will get this error.

Best Answer

There are many different things that can lock the applicationHost.config file and cause powershell commands like New-IISSite to fail.

In this case, you mentioned you deleted the site manually so perhaps you still have IIS Manager open and it is locking the file. I suggest closing IIS Manager.

As described in this blog post on Powershell and IIS, the makers of Octopus Deploy have found that the only reliable solution to the file-locking problem is to wrap any file-altering commands like New-WebAppPool in try-catch blocks and retry these operations multiple times. The source code for a function to do this is found in the blog.