Create HNSC with Powershell and set some settings

This script creates a host named site collection in a web app that is named SharePoint – HNSC.  You can modify it to your hearts content.

 

If you replace Domain with the name of your domain, e.g. say you login with springfield\JoeUser, then you could replace domain with springfield.

The servername can either be a single server or it could be a comma separated list of servers.

The primary site collection admin, secondary site collection admin, their email aliases, and the 3rd site collection admin should be replaced as well, along with the second reference to the servers.

After you make those modifications you can run this from an administrative powershell.

To create a shortcut on your desktop of the server that calls this script, save it in C:\scripts, name it new-hnscsitecollection.ps1 and then make a shortcut that points to the following

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -file “C:\Scripts\New-HNSCSiteCollection.ps1”

Make sure that you right click the new shortcut, click properties, advanced, and then select ‘Run as Administrator’

When you run it

It will prompt you for the name for your site and the URL.  When it comes to these names try and keep the URL short, don’t worry about spaces, the script will remove them.  And you can have a different site name than the URL.

This script disables:

Minimal Download Strategy

Limited-Access user permission mode

and it De-activates the Open in Client Feature

The script enables:

Publishing

SharePoint Standard and Enterprise Features

Office Web apps (this assumes you have office web apps or office online server as it’s known now bound to your farm)

Finally it creates a binding in IIS for all of your servers.

Happy SharePointing and Cheers, Stacy

#################################################################
##              Written by Stacy Simpkins                      ##
##                       for                                   ##
##                   Free Sharing                              ##
#################################################################

$Servers="ServerName"   # enter the servername here, or you might be able to specify a group of servers like this "Server1","Server2" if psremoting is set up
$SharePointSetupAcct = "domain\sp_admin"  #You could replace sp_admin with your setup account name throughout the script


#Verify you are logged in as the SharePoint setup account
If (!("$env:UserDomain\$env:UserName" -eq $SharePointSetupAcct)){
    Throw "Must be logged in as $SharePointSetupAcct"
}


add-pssnapin *SharePoint* -ErrorAction SilentlyContinue
Import-Module WebAdministration #IIS

 


#Validate all servers are available before starting
Write-Host "Testing connectivity to servers"
foreach($s in $Servers){
    if (!(Test-PSRemoting $s)) {
        Write-Host "`tThere was a problem connecting to $s"
        Write-Host "`tScript Terminated"
        Exit #Terminates script if a server is unavailable
    } #end if
    Write-Host "`tSuccessfully connected to $s"
} #end foreach

#Instantiate variables and make clean up company name, if needed


$CompanyNameWithSpaces = Read-Host -prompt "Input the company name for the URL"
$SiteName = Read-Host -prompt "Enter the name for the new Site"
Write-Host "`nSite name set to: $SiteName" -ForegroundColor Cyan
$primarySiteCollectionOwner = "domain\sp_admin"
$primarySiteCollectionOwnerAcctNoDomain = "sp_admin"
$CompanyName=$CompanyNameWithSpaces -replace " ",$null #removes spaces
$SPWebebAppName = "SharePoint - HNSC"
$SPWebebappurl="https://hnsc.domain.com"
$SPWebebappfqdn="https://hnsc.domain.com"
$DatabaseName = "PROD_WSS_Content_" + $CompanyName
$url=$CompanyName
$url=$url -replace " ",$null #removes spaces
$url=$url -ireplace "(:\\|:\\)","://" #flip the slashes
$url=$url + ".domain.com"
$url=$url.ToLower()
if ($url -match "^https?:\/\/") {} else {$url="https://" + $url;Write-Host "`nURL Changed: $url"} #append https://
if ($url -match "^http:\/\/") {
        $url=$url -ireplace "http://","https://";Write-Host "`nURL Changed: $url" #replace http with https
} #end if
$fqdn=$url -ireplace "(http://|https://)",""

#Create Database
Write-Host "`nCreating Database named: $DatabaseName"
New-SPContentDatabase $DatabaseName –WebApplication $SPWebebappurl -WarningSiteCount 0 -MaxSiteCount 1 
Write-Host "`nDatabase named: $DatabaseName `n is mounted to Web Application named: $SPWebebAppName"

#Create Site Collection

# Step 4, create the first HNSC

$primarySiteCollectionOwnerAcct = $primarySiteCollectionOwner
$PrimarySCOwnerEmail = $primarySiteCollectionOwnerAcctNoDomain + "@domain.com"
$SecondaryOwnerAcct = "i:0#.f|fbamembershipprovider|admin"  #This name needs to be in your FBA site already, if you dont want to use FBA you could replace with domain\user
$SedondaryOwnerEmail = "FBA_admin@Domain.com"  #this can really be any alias for any email

$HNSCURL = $url
$HNSCDB = $DatabaseName
$webApp0URL = $SPWebebappurl

Write-Host "`nCreating the new site collection for the Company named: $CompanyNameWithSpaces" -ForegroundColor Green
 
New-SPSite -url $HNSCURL  -Name $SiteName -hostheaderwebapplication $WebApp0URL -ownerAlias $PrimarySiteCollectionOwnerAcct -owneremail $PrimarySCOwnerEmail -SecondaryOwnerAlias $SecondaryOwnerAcct -SecondaryEmail $SecondaryOwnerEmail  -contentDatabase $HNSCDB  -Template STS#0 -WarningAction SilentlyContinue

Write-Host "`nsite collection with URL `t$Url  for the Company named:`t$CompanyNameWithSpaces has been created please update site collection admins and sharepoint permissions, as may be required"

#Adds the binding in IIS

function Add-HostHeader($a,$b) #$SPWebebAppName,$fqdn
{
    Import-Module WebAdministration
    
    #Adds https binding with host header on a given web site
    # PowerShell v2 doesn't support SSL Hostheaders.  Using appcmd instead.
    $AllArgs=@("set","site","$a","/+bindings.[protocol='https',bindingInformation='*:443:$b']")
    &"C:\Windows\System32\inetsrv\appcmd.exe" $AllArgs
    
     
} #End function

    
    
#Adds https host header to $SPWebAppName on all servers (SharePoint does not add automatcially)
Write-Host "`nAdding HTTPS host header"
Invoke-Command -ComputerName $Servers -ScriptBlock ${function:Add-HostHeader} -ArgumentList $SPWebebAppName,$fqdn
Write-Host "`tHTTPS host header successfullly added on $servers"
Write-Host "`nScript Complete"

#################################################################
##       Setting site collection features and settings         ##
##              Written by Stacy Simpkins                      ##
##                       for                                   ##
##                   Free Sharing                              ##
#################################################################


#CONSTANTS
$Servers="ServerName"
$SiteCollAdmin = "domain\AdditionalSiteCollectionAdminUserName"  #Need to replace Additional Site collection Admin name with another site collection admin, this is a 3rd admin
$SearchPage = "https://searchcenter.domain.com/Pages"

#INPUT
$url=$HNSCURL
$url=$url -replace " ",$null #removes spaces
$url=$url -ireplace "(:\\|:\\)","://" #flip the slashes
$url=$url.ToLower()
if ($url -match "^https?:\/\/") {} else {$url="https://" + $url;Write-Host "`nURL Changed: $url"} #append https://
if ($url -match "^http:\/\/") {
        $url=$url -ireplace "http://","https://";Write-Host "`nURL Changed: $url" #replace http with https
} #end if

$fqdn=$url -ireplace "(http://|https://)",""
$SPSite = Get-SPSite $HNSCurl

Write-host "`nStarting to make changes to settings and features for $fqdn" -ForegroundColor Green

#Deactivates site collection Features
Write-Host "`nDisabling site collection features that conflict with Publishing and FBA" -ForegroundColor DarkYellow
Disable-SPFeature "ViewFormPagesLockDown" -url $url -ErrorAction SilentlyContinue -Confirm:$False #Deactivates Limited-access user permission lockdown mode
Disable-SPFeature "MDSFeature" -url $url -ErrorAction SilentlyContinue -Confirm:$False #Deactivates Minimal Download Strategy (MDSFeature)
Disable-SPFeature -identity 87294c72-f260-42f3-a41b-981a2ffce37a  -url $url -ErrorAction SilentlyContinue -Confirm:$False #Deactivates Open Documents in Client Applications by Default (OpenInClient)
Disable-SPFeature -identity 8a4b8de2-6fd8-41e9-923c-c7c3c00f8295  -url $url -ErrorAction SilentlyContinue -Confirm:$False #Deactivates Open Documents in Client Applications by Default (OpenInClient)

#Activates site collection features
Write-Host "`nEnabling site collection features" -ForegroundColor Cyan
Enable-SPFeature "BaseSite" -url $url -ErrorAction SilentlyContinue #Activates SharePoint Server Standard Site Collection features (BaseSite)
Enable-SPFeature "PremiumSite" -url $url -ErrorAction SilentlyContinue #Activates SharePoint Server Enterprise Site Collection features (PremiumSite)
Enable-SPFeature "PublishingSite" -url $url -ErrorAction SilentlyContinue #Activates SharePoint Server Publishing Infrastructure (PublishingSite)
Enable-SPFeature "OfficeWebApps" -url $url -ErrorAction SilentlyContinue #Activates Office Web Apps (OfficeWebApps)
Enable-SPFeature "FBAManagement" -url $url -ErrorAction SilentlyContinue #Activates Forms Based Authentication Management feature (FBAManagement)
$w = Get-SPWeb $url
Get-SPFeature -Web $w | Enable-SPFeature "BaseSite" -url $url -ErrorAction SilentlyContinue #Activates SharePoint Server Standard Site Collection features at the web level (BaseSite)
Get-SPFeature -Web $w |Enable-SPFeature "PremiumSite" -url $url -ErrorAction SilentlyContinue #Activates SharePoint Server Enterprise Site Collection features at the web level (PremiumSite)
#Activates SharePoint Server Publishing Infrastructure at web level (Publishingweb)
$site = Get-SPSite $url
$site | Get-SPWeb -limit all |
ForEach-Object{
write-host "Activating the PublishingWeb feature on " $_.Url
Enable-SPFeature -Identity "PublishingWeb" -Url $_.Url -confirm:$false 
write-host "Activated the PublishingWeb feature on " $_.Url

}



#Site Search Settings
$WebRoot = $SPSite.RootWeb 
$WebRoot.AllProperties["SRCH_ENH_FTR_URL"] = $SearchPage 
$WebRoot.Update()
Write-Host "`nSearch Center Page Set" 

Write-Host "`tSome Awesome Site Collection features successfully enabled"
#Add Site Collection administrator
$WebRoot.ALLUsers.ADD($SiteCollAdmin, "", "", "") #loginName, email, display name, notes
$user = Get-SPUSER -identity $SiteCollAdmin -web $url
$user.IsSiteAdmin = $true
$user.Update()


Write-Host "`nSite Collection Administrators:" $WebRoot.SiteAdministrators | fw

Write-Host "`nScript Complete it is OK to close the window now, have a great day!" -ForegroundColor Cyan