I am remotelly installing SP 2013 via AutoSPInstaller and I am having trouble during script while its try to create site collection.

 - Creating web applications...
 - Web app "Portal" already provisioned.
 - Setting up managed paths for "http://portal.asd.local:80"
  - Setting up explicit managed path "help" at "http://portal.asd.local:80" and HNSCs...
 - Done setting up managed paths at "http://portal.asd.local:80"
 - Applying object cache accounts to "http://portal.asd.local:80"...
 - Done applying object cache accounts to "http://portal.asd.local:80"
 - Checking for Site Collection "http://portal.asd.local"...
 - Creating Site Collection "http://portal.asd.local"...
 - Script halted!

Exception             : System.UnauthorizedAccessException:
                        0x80070005Access denied.
                           at Microsoft.SharePoint.SPGlobal.HandleUnauthorizedAccessException(UnauthorizedAccessExceptio
                        n ex)
                           v Microsoft.SharePoint.Library.SPRequest.CreateSite(Guid gApplicationId, String bstrUrl, Int
                        32 lZone, Guid gSiteId, Guid gDatabaseId, String bstrDatabaseServer, String bstrDatabaseName, S
                        tring bstrDatabaseUsername, String bstrDatabasePassword, String bstrTitle, String bstrDescripti
                        on, UInt32 nLCID, String bstrOwnerLogin, String bstrOwnerUserKey, String bstrOwnerName, String
                        bstrOwnerEmail, String bstrSecondaryContactLogin, String bstrSecondaryContactUserKey, String bs
                        trSecondaryContactName, String bstrSecondaryContactEmail, Boolean bADAccountMode, Boolean bHost
                        HeaderIsSiteName, Int32 iDatabaseVersionMajor, Int32 iDatabaseVersionMinor, Int32 iDatabaseVers
                        ionBuild, Int32 iDatabaseVersionRevision, String bstrSiteSchemaVersion)
                           v Microsoft.SharePoint.Administration.SPSiteCollection.Add(SPContentDatabase database, SPSit
                        eSubscription siteSubscription, String siteUrl, String title, String description, UInt32 nLCID,
                         Int32 compatibilityLevel, String webTemplate, String ownerLogin, String ownerName, String owne
                        rEmail, String secondaryContactLogin, String secondaryContactName, String secondaryContactEmail
                        , String quotaTemplate, String sscRootWebUrl, Boolean useHostHeaderAsSiteName, Boolean override
                           v Microsoft.SharePoint.PowerShell.SPCmdletNewSite.CreateDataObject()
                           v Microsoft.SharePoint.PowerShell.SPNewCmdletBase`1.InternalProcessRecord()
                           v Microsoft.SharePoint.PowerShell.SPCmdlet.ProcessRecord()
TargetObject          : Microsoft.SharePoint.PowerShell.SPCmdletNewSite
CategoryInfo          : InvalidData: (Microsoft.Share...SPCmdletNewSite:SPCmdletNewSite) [New-SPSite], UnauthorizedAcce
FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletNewSite
ErrorDetails          :
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at CreateWebApp, C:\Install\AutoSPInstaller\AutoSPInstaller\AutoSPInstallerFunctions.ps1: line
                        at CreateWebApplications, C:\Install\AutoSPInstaller\AutoSPInstaller\AutoSPInstallerFunctions.p
                        s1: line 2575
                        at Setup-Farm, C:\Install\AutoSPInstaller\AutoSPInstaller\AutoSPInstallerMain.ps1: line 209
                        at , C:\Install\AutoSPInstaller\AutoSPInstaller\AutoSPInstallerMain.ps1: line 408
                        at , : line 1
PipelineIterationInfo : {}
PSMessageDetails      :

| Automated SP2013 install script |
| Started on: 11. 9. 2015 17:49:13 |
| Aborted:    11. 9. 2015 17:50:48 |

I have tried a lot of things

  1. Try to running SharePoint Product Configuration Wizard manually to see if it stabilizes my farm, then try run the script again
  2. Manually set user policy to SuperUser and SuperReader in SP Central Adminsitration to my site collection (as said link on line 2790 in AutoSPInstallerFunctions.ps1 - see Error msg)
  3. checked (System cryptography: FIPS)
  4. Added all avaible DB users all permission (just for control) not working
  5. Set the pool identity from SP_AppPool to Network Service + add SP_Farm into "Log on as a service" and "Log on as a batch" in Local Secuirty Policy
  6. Delete all database, users, web aplications, disconnect the farm via SP Product config wizard and try to run it all over again

None of these working

Is is possible that this problem is due to remote install? because i am getting out of relevant google page to search.

Thank you in advance

/////EDIT////// Source code from AutoSPinstaller that creating it ( @Waqas Sarwar MCSE )

# ===================================================================================
# Func: CreateWebApp
# Desc: Create the web application
# ===================================================================================
Function CreateWebApp([System.Xml.XmlElement]$webApp)
    Get-MajorVersionNumber $xmlinput
    # Look for a managed account that matches the web app type, e.g. "Portal" or "MySiteHost"
    $webAppPoolAccount = Get-SPManagedAccountXML $xmlinput $webApp.Type
    # If no managed account is found matching the web app type, just use the Portal managed account
    if (!$webAppPoolAccount)
        $webAppPoolAccount = Get-SPManagedAccountXML $xmlinput -CommonName "Portal"
        if ([string]::IsNullOrEmpty($webAppPoolAccount.username)) {throw " - `"Portal`" managed account not found! Check your XML."}
    $webAppName = $webApp.name
    $appPool = $webApp.applicationPool
    $dbPrefix = Get-DBPrefix $xmlinput
    $database = $dbPrefix+$webApp.Database.Name
    $dbServer = $webApp.Database.DBServer
    # Check for an existing App Pool
    $existingWebApp = Get-SPWebApplication | Where-Object { ($_.ApplicationPool).Name -eq $appPool }
    $appPoolExists = ($existingWebApp -ne $null)
    # If we haven't specified a DB Server then just use the default used by the Farm
    If ([string]::IsNullOrEmpty($dbServer))
        $dbServer = $xmlinput.Configuration.Farm.Database.DBServer
    $url = $webApp.url
    $port = $webApp.port
    $useSSL = $false
    $installedOfficeServerLanguages = (Get-Item "HKLM:\Software\Microsoft\Office Server\$env:spVer.0\InstalledLanguages").GetValueNames() | ? {$_ -ne ""}
    # Strip out any protocol value
    If ($url -like "https://*") {$useSSL = $true}
    $hostHeader = $url -replace "http://","" -replace "https://",""
    if (((Get-WmiObject Win32_OperatingSystem).Version -like "6.2*" -or (Get-WmiObject Win32_OperatingSystem).Version -like "6.3*") -and ($env:spVer -eq "14"))
        Write-Host -ForegroundColor White " - Skipping setting the web app directory path name (not currently working on Windows 2012 w/SP2010)..."
        $pathSwitch = @{}
        # Set the directory path for the web app to something a bit more friendly
        # Get the default root location for web apps
        $iisWebDir = (Get-ItemProperty "IIS:\Sites\Default Web Site\" -name physicalPath -ErrorAction SilentlyContinue) -replace ("%SystemDrive%","$env:SystemDrive")
        if (!([string]::IsNullOrEmpty($iisWebDir)))
            $pathSwitch = @{Path = "$iisWebDir\wss\VirtualDirectories\$webAppName-$port"}
        else {$pathSwitch = @{}}
    # Only set $hostHeaderSwitch to blank if the UseHostHeader value exists has explicitly been set to false
    if (!([string]::IsNullOrEmpty($webApp.UseHostHeader)) -and $webApp.UseHostHeader -eq $false)
        $hostHeaderSwitch = @{}
    else {$hostHeaderSwitch = @{HostHeader = $hostHeader}}
    if (!([string]::IsNullOrEmpty($webApp.useClaims)) -and $webApp.useClaims -eq $false)
        # Create the web app using Classic mode authentication
        $authProviderSwitch = @{}
    else # Configure new web app to use Claims-based authentication
        If ($($webApp.useBasicAuthentication) -eq $true)
            $authProvider = New-SPAuthenticationProvider -UseWindowsIntegratedAuthentication -UseBasicAuthentication
            $authProvider = New-SPAuthenticationProvider -UseWindowsIntegratedAuthentication
        $authProviderSwitch = @{AuthenticationProvider = $authProvider}
        If ((Gwmi Win32_OperatingSystem).Version -like "6.0*") # If we are running Win2008 (non-R2), we may need the claims hotfix
            [bool]$claimsHotfixRequired = $true
            Write-Host -ForegroundColor Yellow " - Web Applications using Claims authentication require an update"
            Write-Host -ForegroundColor Yellow " - Apply the http://go.microsoft.com/fwlink/?LinkID=184705 update after setup."
    if ($appPoolExists)
        $appPoolAccountSwitch = @{}
        $appPoolAccountSwitch = @{ApplicationPoolAccount = $($webAppPoolAccount.username)}
    $getSPWebApplication = Get-SPWebApplication | Where-Object {$_.DisplayName -eq $webAppName}
    If ($getSPWebApplication -eq $null)
        Write-Host -ForegroundColor White " - Creating Web App `"$webAppName`""
        New-SPWebApplication -Name $webAppName -ApplicationPool $appPool -DatabaseServer $dbServer -DatabaseName $database -Url $url -Port $port -SecureSocketsLayer:$useSSL @hostHeaderSwitch @appPoolAccountSwitch @authProviderSwitch @pathSwitch | Out-Null
        If (-not $?) { Throw " - Failed to create web application" }
    Else {Write-Host -ForegroundColor White " - Web app `"$webAppName`" already provisioned."}
    SetupManagedPaths $webApp
    If ($useSSL)
        $SSLHostHeader = $hostHeader
        $SSLPort = $port
        $SSLSiteName = $webAppName
        if (((Get-WmiObject Win32_OperatingSystem).Version -like "6.2*" -or (Get-WmiObject Win32_OperatingSystem).Version -like "6.3*") -and ($env:spVer -eq "14"))
            Write-Host -ForegroundColor White " - Assigning certificate(s) in a separate PowerShell window..."
            Start-Process -FilePath "$PSHOME\powershell.exe" -Verb RunAs -ArgumentList "-Command `". $env:dp0\AutoSPInstallerFunctions.ps1`; AssignCert $SSLHostHeader $SSLPort $SSLSiteName; Start-Sleep 10`"" -Wait
        else {AssignCert $SSLHostHeader $SSLPort $SSLSiteName}

    # If we are provisioning any Office Web Apps, Visio, Excel, Access or PerformancePoint services, we need to grant the generic app pool account access to the newly-created content database
    # Per http://technet.microsoft.com/en-us/library/ff829837.aspx and http://autospinstaller.codeplex.com/workitem/16224 (thanks oceanfly!)
    If ((ShouldIProvision $xmlinput.Configuration.OfficeWebApps.ExcelService -eq $true) -or `
        (ShouldIProvision $xmlinput.Configuration.OfficeWebApps.PowerPointService -eq $true) -or `
        (ShouldIProvision $xmlinput.Configuration.OfficeWebApps.WordViewingService -eq $true) -or `
        (ShouldIProvision $xmlinput.Configuration.EnterpriseServiceApps.VisioService -eq $true) -or `
        (ShouldIProvision $xmlinput.Configuration.EnterpriseServiceApps.ExcelServices -eq $true) -or `
        (ShouldIProvision $xmlinput.Configuration.EnterpriseServiceApps.AccessService -eq $true) -or `
        (ShouldIProvision $xmlinput.Configuration.EnterpriseServiceApps.AccessServices -eq $true) -or `
        (ShouldIProvision $xmlinput.Configuration.EnterpriseServiceApps.PerformancePointService -eq $true))
        $spservice = Get-SPManagedAccountXML $xmlinput -CommonName "spservice"
        Write-Host -ForegroundColor White " - Granting $($spservice.username) rights to `"$webAppName`"..." -NoNewline
        $wa = Get-SPWebApplication | Where-Object {$_.DisplayName -eq $webAppName}
        Write-Host -ForegroundColor White "OK."
    if ($webApp.GrantCurrentUserFullControl -eq $true)
        $currentUser = "$env:USERDOMAIN\$env:USERNAME"
        $wa = Get-SPWebApplication | Where-Object {$_.DisplayName -eq $webAppName}
        if ($wa.UseClaimsAuthentication -eq $true) {$currentUser = 'i:0#.w|' + $currentUser}
        Set-WebAppUserPolicy $wa $currentUser "$env:USERNAME" "Full Control"
    ConfigureObjectCache $webApp

    if ($webApp.SiteCollections.SelectSingleNode("SiteCollection")) # Only go through these steps if we actually have a site collection to create
        ForEach ($siteCollection in $webApp.SiteCollections.SiteCollection)
            $dbPrefix = Get-DBPrefix $xmlinput
            $getSPSiteCollection = $null
            $siteCollectionName = $siteCollection.Name
            $siteURL = $siteCollection.siteURL
            $CompatibilityLevel = $siteCollection.CompatibilityLevel
            if (!([string]::IsNullOrEmpty($CompatibilityLevel))) # Check the Compatibility Level if it's been specified
                $CompatibilityLevelSwitch = @{CompatibilityLevel = $CompatibilityLevel}
            else {$CompatibilityLevelSwitch = @{}}
            if (!([string]::IsNullOrEmpty($($siteCollection.CustomDatabase)))) # Check if we have specified a non-default content database for this site collection
                $siteDatabase = $dbPrefix+$siteCollection.CustomDatabase
            else # Just use the first, default content database for the web application
                $siteDatabase = $database
            # If an OwnerAlias has been specified, make it the primary, and the currently logged-in account the secondary. Otherwise, make the app pool account for the web app the primary owner
            if (!([string]::IsNullOrEmpty($($siteCollection.Owner))))
                $ownerAlias = $siteCollection.Owner
                $ownerAlias = $webAppPoolAccount.username
            $LCID = $siteCollection.LCID
            $siteCollectionLocale = $siteCollection.Locale
            $siteCollectionTime24 = $siteCollection.Time24
            # If a template has been pre-specified, use it when creating the Portal site collection; otherwise, leave it blank so we can select one when the portal first loads
            $template = $siteCollection.template
            If (($template -ne $null) -and ($template -ne ""))
                $templateSwitch = @{Template = $template}
            else {$templateSwitch = @{}}
            if ($siteCollection.HostNamedSiteCollection -eq $true)
                $hostHeaderWebAppSwitch = @{HostHeaderWebApplication = $($webApp.url)+":"+$($webApp.port)}
            else {$hostHeaderWebAppSwitch = @{}}
            Write-Host -ForegroundColor White " - Checking for Site Collection `"$siteURL`"..."
            $getSPSiteCollection = Get-SPSite -Limit ALL | Where-Object {$_.Url -eq $siteURL}
            If (($getSPSiteCollection -eq $null) -and ($siteURL -ne $null))
                # Verify that the Language we're trying to create the site in is currently installed on the server
                $culture = [System.Globalization.CultureInfo]::GetCultureInfo(([convert]::ToInt32($LCID)))
                $cultureDisplayName = $culture.DisplayName
                If (!($installedOfficeServerLanguages | Where-Object {$_ -eq $culture.Name}))
                    Write-Warning "You must install the `"$culture ($cultureDisplayName)`" Language Pack before you can create a site using LCID $LCID"
                    $siteDatabaseExists = Get-SPContentDatabase -Identity $siteDatabase -ErrorAction SilentlyContinue
                    if (!$siteDatabaseExists)
                        Write-Host -ForegroundColor White " - Creating new content database `"$siteDatabase`"..."
                        New-SPContentDatabase -Name $siteDatabase -WebApplication (Get-SPWebApplication $webApp.url) | Out-Null
                    Write-Host -ForegroundColor White " - Creating Site Collection `"$siteURL`"..."
                    $site = New-SPSite -Url $siteURL -OwnerAlias $ownerAlias -SecondaryOwner $env:USERDOMAIN\$env:USERNAME -ContentDatabase $siteDatabase -Description $siteCollectionName -Name $siteCollectionName -Language $LCID @templateSwitch @hostHeaderWebAppSwitch @CompatibilityLevelSwitch -ErrorAction Stop

                    # JDM Not all Web Templates greate the default SharePoint Croups that are made by the UI
                    # JDM These lines will insure that the the approproprate SharePoint Groups, Owners, Members, Visitors are created
                    $primaryUser = $site.RootWeb.EnsureUser($ownerAlias)
                    $secondaryUser = $site.RootWeb.EnsureUser("$env:USERDOMAIN\$env:USERNAME")
                    $title = $site.RootWeb.title
                    Write-Host -ForegroundColor White " - Ensuring default groups are created..."
                    $site.RootWeb.CreateDefaultAssociatedGroups($primaryUser, $secondaryUser, $title)

                    # Add the Portal Site Connection to the web app, unless of course the current web app *is* the portal
                    # Inspired by http://www.toddklindt.com/blog/Lists/Posts/Post.aspx?ID=264
                    $portalWebApp = $xmlinput.Configuration.WebApplications.WebApplication | Where {$_.Type -eq "Portal"} | Select-Object -First 1
                    $portalSiteColl = $portalWebApp.SiteCollections.SiteCollection | Select-Object -First 1
                    If ($site.URL -ne $portalSiteColl.siteURL)
                        Write-Host -ForegroundColor White " - Setting the Portal Site Connection for `"$siteCollectionName`"..."
                        $site.PortalName = $portalSiteColl.Name
                        $site.PortalUrl = $portalSiteColl.siteUrl
                    If ($siteCollectionLocale)
                        Write-Host -ForegroundColor White " - Updating the locale for `"$siteCollectionName`" to `"$siteCollectionLocale`"..."
                        $site.RootWeb.Locale = [System.Globalization.CultureInfo]::CreateSpecificCulture($siteCollectionLocale)
                    If ($siteCollectionTime24)
                        Write-Host -ForegroundColor White " - Updating 24 hour time format for `"$siteCollectionName`" to `"$siteCollectionTime24`"..."
                        $site.RootWeb.RegionalSettings.Time24 = $([System.Convert]::ToBoolean($siteCollectionTime24))
            Else {Write-Host -ForegroundColor White " - Skipping creation of site `"$siteCollectionName`" - already provisioned."}
            if ($siteCollection.HostNamedSiteCollection -eq $true)
                Add-LocalIntranetURL ($siteURL)
                # Updated so that we don't add URLs to the local hosts file of a server that's not running the Foundation Web Application service
                if ($xmlinput.Configuration.WebApplications.AddURLsToHOSTS -eq $true -and !(($xmlinput.Configuration.Farm.Services.SelectSingleNode("FoundationWebApplication")) -and !(ShouldIProvision $xmlinput.Configuration.Farm.Services.FoundationWebApplication -eq $true)))
                    # Add the hostname of this host header-based site collection to the local HOSTS so it's immediately resolvable locally
                    # Strip out any protocol and/or port values
                    $hostname,$null = $siteURL -replace "http://","" -replace "https://","" -split ":"
                    AddToHOSTS $hostname
        Write-Host -ForegroundColor Yellow " - No site collections specified for $($webapp.url) - skipping."

# ===================================================================================
  • can you share the piece of code which create the Site collection? i think at line 408 or 209
    – Waqas Sarwar MVP
    Sep 11, 2015 at 20:49
  • That could be because your "SharePoint Web Services" site was stopped. Apr 7, 2016 at 10:07
  • I'm confirmed that the issue happens because like @AlexBurdin said SharePoint Web Services is stopped. AutoSPInstaller stops it as part of the "initial farm/server config" after creating the Configuration Database, If you start the IIS site before it creates the site collection it works (you gotta watch for it to happen and restart it immediately). What I don't know is why this happens on some servers but not others.
    – shufler
    May 30, 2017 at 19:10
  • @shufler, I described this behavior a long time ago and proposed a change for AutoSPInstaller's owner and maintainer. Vote if you feel like it needs to be changed: autospinstaller.codeplex.com/workitem/22232 May 31, 2017 at 10:44
  • @AlexBurdin "If you removed or didn't have "Default Web Site" then after set up of SharePoint farm newly created "SharePoint Web Services" will have an ID = 1 in IIS Sites." --- ohhhhh. This is what happened in this case. I had deleted W3SVC1
    – shufler
    Jun 2, 2017 at 0:56

1 Answer 1


If you removed or didn't have "Default Web Site" then after set up of SharePoint farm newly created "SharePoint Web Services" will have an ID = 1 in IIS Sites.

When you try to provision first Web App, there's a call to "Stop-DefaultWebsite" function, which stops IIS site with ID = 1, so "SharePoint Web Services" site will be stopped. Later, on site collection creation step you'll end up with AccessDenied exception because STS is not available.

As described above, the problem is in "Stop-DefaultWebsite" function, because it tries to find default site by ID = 1, but site with ID = 1 might not be the Default one (e.g. SharePoint Web Services).

I've reported issue here: http://autospinstaller.codeplex.com/workitem/22232 Workaround mentioned there too. Seems like this issue affects significant number of people. Vote on 'codeplex' if you feel like it needs to be changed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.