domingo, 17 de julio de 2016

Parte 7 – Sharepoint 2016 Creación del Search Service

Indice de Instalación de Sharepoint 2016

En esta parte instalaré el servicio de Search. La arquitectura será la siguiente

image

Crear un folder en “D:\Data\Microsoft\SearchSharepointIndex” en CADA SERVER de la granja.

Dar permisos a los grupos WSS_ADMIN_WPG, WSS_WPG y WSS_RESTRICTED_WPG

También dar permisos sobre el folder:

D:\Data\Microsoft\Microsoft Office Servers\16.0\Data\Office Server\Applications

Al finalizar la ejecución del script tendrá la siguiente configuración

image

Descargar Script

$searchSAName = "Search Service"
$saAppPoolName = "SharePoint Web Services Default"
$searchMachines = @("DNS_WebFrontEndServer","DNS_ApplicationServer")

#El WebFront End Server tiene los siguientes servicios: Query Processing Component
$searchQueryMachine = "DNS_WebFrontEndServer"

#El Application Server tiene los siguientes servicios: Admin Component,Analytics Component,Content Processing Component,Crawl Component, Index Component
$searchCrawlerMachine = "DNS_ApplicationServer"

$indexLocation = "D:\Data\Microsoft\SearchSharepointIndex"
#VER LINEAS 32, 37.

#ALIAS del sql server
$databaseServerName = "SQLSP2016"
$searchDatabaseName = "Sharepoint_Search"


##########################
# Search Service - START #
##########################
#
Write-Host "Creando Search Service y Proxy..."
Write-Host "  Iniciando Services..."
foreach ($machine in $searchMachines)
{
    Write-Host "    Iniciando Search Services en $machine"
    Start-SPEnterpriseSearchQueryAndSiteSettingsServiceInstance $machine
    Start-SPEnterpriseSearchServiceInstance $machine   
}

############CREO EL SEARCH SERVICE APPLICATION ##############

Write-Host "  Creando Search Service Application..."
$searchApp = Get-SPEnterpriseSearchServiceApplication -Identity $searchSAName -ErrorAction SilentlyContinue
if (!$searchApp)
{
    $searchApp = New-SPEnterpriseSearchServiceApplication -Name $SearchSAName -ApplicationPool     $saAppPoolName -DatabaseServer $databaseServerName -DatabaseName $searchDatabaseName
}

$searchInstanceCrawl = Get-SPEnterpriseSearchServiceInstance -Identity $searchCrawlerMachine
$searchInstanceCrawlQuery = Get-SPEnterpriseSearchServiceInstance -Identity $searchQueryMachine

Start-SPEnterpriseSearchServiceInstance -Identity $searchInstanceCrawl
Start-SPEnterpriseSearchServiceInstance -Identity $searchInstanceCrawlQuery

#espero 60 segundos, hasta que inicie
Start-Sleep -s 60

#############################
# Define the search topology
Write-Host "  Defining the Search Topology..."
$initialSearchTopology = $searchApp | Get-SPEnterpriseSearchTopology -Active
$newSearchTopology = $searchApp | New-SPEnterpriseSearchTopology

Start-Sleep -s 60

# Create search components
Write-Host "  Creating Admin Component..."
New-SPEnterpriseSearchAdminComponent -SearchTopology $newSearchTopology -SearchServiceInstance $searchInstanceCrawl

Start-Sleep -s 60

Write-Host "  Creating Analytics Component..."
New-SPEnterpriseSearchAnalyticsProcessingComponent -SearchTopology $newSearchTopology -SearchServiceInstance $searchInstanceCrawl

Start-Sleep -s 60

Write-Host "  Creating Content Processing Component..."
New-SPEnterpriseSearchContentProcessingComponent -SearchTopology $newSearchTopology -SearchServiceInstance $searchInstanceCrawl

Start-Sleep -s 60

Write-Host "  Creating Crawl Component..."
New-SPEnterpriseSearchCrawlComponent -SearchTopology $newSearchTopology -SearchServiceInstance $searchInstanceCrawl

Write-Host "  Creating Index Component..."
New-SPEnterpriseSearchIndexComponent -SearchTopology $newSearchTopology -SearchServiceInstance

$searchInstanceCrawlQuery -RootDirectory $indexLocation

Start-Sleep -s 60

Write-Host "  Creating Query Processing Component..."
New-SPEnterpriseSearchQueryProcessingComponent -SearchTopology $newSearchTopology -SearchServiceInstance $searchInstanceCrawlQuery

Start-Sleep -s 60

Write-Host "  Activating the new topology..."
$newSearchTopology.Activate()

Write-Host "  Creating Search Application Proxy..."
$searchProxy = Get-SPEnterpriseSearchServiceApplicationProxy -Identity "$searchSAName Proxy" -ErrorAction SilentlyContinue
Start-Sleep -s 60
if (!$searchProxy)
{
    New-SPEnterpriseSearchServiceApplicationProxy -Name "$searchSAName Proxy" -SearchApplication $searchSAName
}
########################
# Search Service - END #
########################

Parte 6–SharePoint 2016 Creación de web application

Indice de Instalación de Sharepoint 2016

En esta parte, creo un web application http://intra.contoso.com

Uso 3 cuentas:

  • svcspwapp: Sharepoint Web Application Account, cuenta de identidad para ejecutar los application pools del IIS
  • svcspsprusr:  Sharepoint SuperUser, cuenta para acceder al web application con Full Read access (auditoria/caching)
  • svcspsprread: Sharepoint SuperReader cuenta para acceder al web application con Full Control access (auditoria/caching)

 

Descargar Script

$ver = $host | select version

if($Ver.version.major -gt 1) {$Host.Runspace.ThreadOptions = "ReuseThread"}

if(!(Get-PSSnapin Microsoft.SharePoint.PowerShell -ea 0))
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell
}

Write-Progress -Activity "Creando Web Application" -Status "Seteando Variables"
##CONFIGURACIÓN

# Web Application URL
$WebApplicationURL = "http://intra.contoso.com"

# Nombre para el SharePoint Web Application
$WebApplicationName = "Intra Web Application"

# Content Database para el web application
$ContentDatabase = "Intra_ContentDB1"

# Nombre para el Application Pool
$ApplicationPoolDisplayName = "Intra App Pool"

# Identidad para el Application Pool (domain\user)
$ApplicationPoolIdentity = "CONTOSO\svcspwapp"

# Password para el Application Pool
$ApplicationPoolPassword = "xxxxxxxxxx"

# Cuenta para Super Reader
$PortalSuperReader = "i:0#.w|CONTOSO\svcspsprread"

# Cuenta para Super User
$PortalSuperUser = "i:0#.w|CONTOSO\svcspsprusr"

Write-Progress -Activity "Creando Web Application" -Status "Loading Functions"


Function CrearClaimsWebApp($WebApplicationName, $WebApplicationURL, $ContentDatabase, $HTTPPort)
{
    $ap = New-SPAuthenticationProvider
   
    if($AppPoolUsed -eq $True)
    {
        Write-Progress -Activity "Creating Web Application" -Status "Using Application Pool With Existing Web Applications"
        Set-Variable -Name WebApp -Value (New-SPWebApplication -ApplicationPool $ApplicationPoolDisplayName -Name $WebApplicationName -url $WebApplicationURL -port $HTTPPort -DatabaseName $ContentDatabase -HostHeader $hostHeader -AuthenticationProvider $ap) -Scope Script
       

        Write-Progress -Activity "Creating Web Application" -Status "Configuring Object Cache Accounts"
        SetObjectCache
       
    }
    else
    {       
        Write-Progress -Activity "Creating Web Application" -Status "Using Application Pool With No Existing Web Applications"
        Set-Variable -Name WebApp -Value (New-SPWebApplication -ApplicationPool $ApplicationPoolDisplayName -ApplicationPoolAccount $AppPoolManagedAccount.Username -Name $WebApplicationName -url $WebApplicationURL -port $HTTPPort -DatabaseName $ContentDatabase -HostHeader $hostHeader -AuthenticationProvider $ap) -Scope Script
       
        Write-Progress -Activity "Creating Web Application" -Status "Configuring Object Cache Accounts"
        SetObjectCache
       
    }
}

Function ValidarURL($WebApplicationURL)
{
    if(get-spwebapplication $WebApplicationURL -ErrorAction SilentlyContinue)
    {
        Write-Progress -Activity "Creando Web Application" -Status "Abortando proceso debido a un conflicto de URL"
        Write-Host "Abortando: Web Application $WebApplicationURL ya existe" -ForegroundColor Red
      
        #Seteo el valor CriticalError a $True resultado en NO crear nada
        Set-Variable -Name CriticalError -Value $True
    }  
    elseif($WebApplicationURL.StartsWith("http://"))
        {
            Set-Variable HostHeader -Value ($WebApplicationURL.Substring(7)) -Scope Script
            Set-Variable -Name HTTPPort -Value "80" -Scope Script
        }
        elseif($WebApplicationURL.StartsWith("https://"))
        {
            Set-Variable HostHeader -Value ($WebApplicationURL.Substring(8)) -Scope Script
            Set-Variable -Name HTTPPort -Value "443" -Scope Script
        }
}

Function ValidarAppPool($AppPoolName, $WebApplicationURL)
{
    $CurrentErrorActionPreference = $ErrorActionPreference
    $ErrorActionPreference = "SilentlyContinue"

    #Verifica si existe un application pool con el nombre pasado como parametro   
    $TestAppPool = Get-WebAppPoolState $AppPoolName

    if(Get-SPServiceApplicationPool $AppPoolName)
    {
        $AppPools = Get-SPWebApplication | select ApplicationPool

        if($AppPools)
        {
            foreach($Pool in $AppPools)
            {
              
                [Array]$Poolchild = $Poolchild += ($Pool.ApplicationPool.DisplayName)

                if($Poolchild.Contains($ApplicationPoolDisplayName))
                {
                    Set-Variable -Name AppPoolUsed -Value $True -Scope Script
                }

                else
                {
                    Set-Variable -Name AppPoolUsed -Value $False -Scope Script
                }
            }
        }
       
        Set-Variable -Name AppPool -Value (Get-SPServiceApplicationPool $AppPoolName) -scope Script

        Set-Variable -Name AppPoolManagedAccount -Value (Get-SPManagedAccount | ? {$_.username -eq ($AppPool.ProcessAccountName)}) -scope Script
    }
    elseif($TestAppPool)
    {
        Write-Host "Aborting: Application Pool $AppPoolName already exists on the server and is not a SharePoint Application Pool `n`rWeb Application `"$WebApplicationURL`" will not be created" -ForegroundColor Red
        Set-Variable -Name CriticalError -Value $True
    }
    elseif(!($TestAppPool))
    {
        ValidarManagedAccount $ApplicationPoolIdentity

        if($ManagedAccountExists -eq $True)
        {
            Write-Host "Creating New App Pool using Existing Managed Account"
            Set-Variable -Name AppPoolManagedAccount -Value (Get-SPManagedAccount $ApplicationPoolIdentity | select username) -scope "Script"

            Set-Variable -Name AppPool -Value (New-SPServiceApplicationPool -Name $ApplicationPoolDisplayName -Account $ApplicationPoolIdentity) -scope "Script"
        }
        else
        {
            Write-Host "Creating New Managed Account And App Pool"
            $AppPoolCredentials = New-Object System.Management.Automation.PSCredential $ApplicationPoolIdentity, (ConvertTo-SecureString $ApplicationPoolPassword -AsPlainText -Force)
           
            Set-Variable -Name AppPoolManagedAccount -Value (New-SPManagedAccount -Credential $AppPoolCredentials) -scope "Script"
           
            Set-Variable -Name AppPool -Value (New-SPServiceApplicationPool -Name $ApplicationPoolDisplayName -Account (get-spmanagedaccount $ApplicationPoolIdentity)) -scope "Script"
        }

    }
   
    $ErrorActionPreference = $CurrentErrorActionPreference

}

Function ValidarManagedAccount($ApplicationPoolIdentity)
{
    if(Get-SPManagedAccount $ApplicationPoolIdentity -ErrorAction SilentlyContinue)
    {
        Set-Variable -Name ManagedAccountExists -Value $True -Scope Script
    }
    else
    {
        Set-Variable -Name ManagedAccountExists -Value $False -Scope Script
    }
}

Function LimpiarVariables
{
    $CurrentErrorActionPreference = $ErrorActionPreference
    $ErrorActionPreference = "SilentlyContinue"

    Remove-Variable $CriticalError -ErrorAction SilentlyContinue
    $ErrorActionPreference = $CurrentErrorActionPreference
}

Function SetObjectCache
{
    $WebApp.Properties["portalsuperuseraccount"] = $PortalSuperUser
    $WebApp.Properties["portalsuperreaderaccount"] = $PortalSuperReader
    
    #Creo una nueva policy para el Super User
    $SuperUserPolicy = $WebApp.Policies.Add($PortalSuperUser, "Portal Super User Account")
    #Asigno Full Control al Super User
    $SuperUserPolicy.PolicyRoleBindings.Add($WebApp.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullControl))
   
    #Creo una nueva policy para el Super Reader
    $SuperReaderPolicy = $WebApp.Policies.Add($PortalSuperReader, "Portal Super Reader Account")   
    #Asigno Full Read al Super Reader
    $SuperReaderPolicy.PolicyRoleBindings.Add($WebApp.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullRead))

    #Commit these changes to the web application
    $WebApp.Update()
}


Write-Progress -Activity "Creando Web Application" -Status "Validando las URL del Web Application"
ValidarURL $WebApplicationURL

Write-Progress -Activity "Creando Web Application" -Status "Validando los Pools de los Application"
ValidarAppPool $ApplicationPoolDisplayName $WebApplicationURL


if(!($CriticalError))
{
    Write-Progress -Activity "Creando Web Application" -Status "Creando Claims-Based Web Application"
    CrearClaimsWebApp $WebApplicationName $WebApplicationURL $ContentDatabase $HTTPPort
}

Parte 4–Sharepoint 2016 - Sharepoint Web Services Default Application Pool

Indice de Instalación de Sharepoint 2016

A continuación se crea el Application Pool para los services applications. Puedes crear N cuentas dependiendo del tipo de seguridad que quieres implementar para tus services applications.

Descargar Script

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
$AppPoolName = "SharePoint Web Services Default"
$AppPoolUserName = "CONTOSO\svcspsvcapps"
$SAAppPool = Get-SPServiceApplicationPool -Identity $AppPoolName -EA 0
if($SAAppPool -eq $null)
{
    $AppPoolAccount = Get-SPManagedAccount -Identity $AppPoolUserName -EA 0
    if($AppPoolAccount -eq $null)
    {
        $AppPoolCred = Get-Credential $AppPoolUserName
        $AppPoolAccount = New-SPManagedAccount -Credential $AppPoolCred -EA 0
    }
    $AppPoolAccount = Get-SPManagedAccount -Identity $AppPoolUserName -EA 0
    if($AppPoolAccount -eq $null)
    {
        Write-Host "Cannot create or find the managed account $appPoolUserName, please ensure the account exists."
        Exit -1
    }
    New-SPServiceApplicationPool -Name $AppPoolName -Account $AppPoolAccount -EA 0 > $null
    Write-Host "Se ha creado correctamente la cuenta default de app pool"
}
Else
{
    Write-Host "Fallo la creación de la cuenta"
}

Parte 5–Sharepoint 2016–Creación de Usage and Health Data Collection Service

Indice de Instalación de Sharepoint 2016

En esta parte crearemos el servicio de Usage and Health Data Collection, para ello crea en CADA servidor de la granja, una estructura de carpetas en la partición D:\

Estructura: D:\Data\ServerLogs\Sharepoint\

Recomendación: configura los logs del IIS en el siguiente path D:\Data\ServerLogs\IIS\

El servicio SPTraceV4 lo dejé configurado para que se ejecute con Local Service.

image

Verifica que la cuenta de Farm esté en los siguientes grupos: WSS_WPG, WSS_RESTRICTED_WPG, WSS_ADMIN_WPG, Performance Log Users, Performance Monitor Users

Verifica que Local Services y los grupos WSS_WPG, WSS_RESTRICTED_WPG, WSS_ADMIN_WPG tengan permisos de write sobre la carpeta D:\Data\ServerLogs\Sharepoint\

image

Descargar Script

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

#configuration initial
$usageSAName = “Usage and Health Data Collection Service”
$stateSAName = “State Service”
$stateServiceDatabaseName = “Sharepoint_StateServices”
$saAppPoolName = “SharePoint Web Services Default”

# Configure the web analytics and health data collection service before creating the service
Set-SPUsageService -LoggingEnabled 1 -UsageLogLocation "D:\Data\ServerLogs\Sharepoint\" -UsageLogMaxSpaceGB 4

# Usage Service
Write-Host "Creating Usage Service"
$serviceInstance = Get-SPUsageService
New-SPUsageApplication -Name $usageSAName -DatabaseName “Sharepoint_UsageService” -UsageService $serviceInstance > $null

# State Service
Write-Host "Creating State Service and Proxy..."
$stateServiceDatabase = New-SPStateServiceDatabase -Name $stateServiceDatabaseName
$stateSA = New-SPStateServiceApplication -Name $stateSAName -Database $stateServiceDatabase

# Proxy
New-SPStateServiceApplicationProxy -ServiceApplication $stateSA -Name “$stateSAName Proxy” -DefaultProxyGroup

Get-SPStateServiceApplication | Select Name
Get-SPStateServiceApplicationProxy | Select Name

##SET DIAGNOSTICCONFIG
#seteo el tipo de logueo y severidad que quiero monitorear, puede variar en tu ambiente el tracing que quieres realizar
Set-SPDiagnosticConfig -LogLocation "D:\Data\ServerLogs\Sharepoint" -LogMaxDiskSpaceUsageEnabled -EventLogFloodProtectionEnabled -LogDiskSpaceUsageGB 4 -DaysToKeepLogs 7
Set-SPLogLevel -EventSeverity warning -TraceSeverity high

Verifica  la configuración en el central administration.

image

image

image[7]

El monitoreo de eventos lo definí de la siguiente manera:

Get-SPUsageDefinition

image

image

Cada evento lo puedes setear de manera particular en el caso que quieras mantener por un tiempo más los logging.

En el caso que quieras cambiar la cuenta de usuario del servicio SPTraceV4, puedes ejecutar el siguiente script.

 

# Get the tracing service.
$farm = Get-SPFarm
$tracingService = $farm.Services | where {$_.Name -eq "SPTraceV4"}
# Get the "svc_sp_services" managed account.
$managedAccount = Get-SPManagedAccount "CONTOSO\cuenta de usuario"
# Set the tracing service to run under the managed account.
$tracingService.ProcessIdentity.CurrentIdentityType = "SpecificUser"
$tracingService.ProcessIdentity.ManagedAccount = $managedAccount
$tracingService.ProcessIdentity.Update()
# This actually changes the "Run As" account of the Windows service.
$tracingService.ProcessIdentity.Deploy()

sábado, 16 de julio de 2016

Parte 3 - Sharepoint 2016 conectándose a la granja

Indice de Instalación de Sharepoint 2016

En esta parte, vamos a conectar el WebFront End “Custom” a la granja previamente creada

Ingresar al WebFront “Custom” con una cuenta con privilegios de sysadmin sobre el SQL Server. Mi recomendación es ingresar con la cuenta de Farm para evitar problemas futuros.

Prueba la conexión al SQL Server, mediante un archivo .udl https://blogs.technet.microsoft.com/michaelgriswold/2014/01/06/the-easy-way-to-test-sql-connectivity/

Algunas definiciones:

  • El WebFront End “Custom” tendrá un host de Distributed Cache
  • Se deshabilitará Loopback Check.

Ejecuta una consola de PowerShell_ISE como ADMINISTRADOR, y ejecutar el siguiete script

%windir%\system32\WindowsPowerShell\v1.0\PowerShell_ISE.exe

Descargar script de conexión a la granja

############################################################
#    Crear un farm de SharePoint 2016
#    Creado por Christian Azcon
############################################################
$ver = $host | select version
if ($ver.Version.Major -gt 1)  {$Host.Runspace.ThreadOptions = "ReuseThread"}
Add-PsSnapin Microsoft.SharePoint.PowerShell

########################################
# Defino Settings #
########################################

#SQL Alias
$AliasName = "SQLSP2016" 
# Cambia el nombre por el del SQL--> FQDN
$ServerName = "HostNameSQLServer.contoso.net"
$configPassphrase = 'SeguridadFraseSharepoint2016'
$s_configPassphrase = (ConvertTo-SecureString -String $configPassphrase -AsPlainText -force)
 
$serverDB = $AliasName
$dbConfig = "Sharepoint_Configuration"

########################################
# Creo the SQL Alias
########################################

$x86 = "HKLM:\Software\Microsoft\MSSQLServer\Client\ConnectTo"
$x64 = "HKLM:\Software\Wow6432Node\Microsoft\MSSQLServer\Client\ConnectTo"
 
#Verifico si la clave ConnectTo ya existe, y la creo en caso contrario
if ((test-path -path $x86) -ne $True)
{
    write-host "$x86 no existe"
    New-Item $x86
}
if ((test-path -path $x64) -ne $True)
{
    write-host "$x64 no existe"
    New-Item $x64
}
 
#Defino el tipo de alias
$TCPAlias = ("DBMSSOCN," + $ServerName)
 
#Creo el TCP/IP Aliases
Write-Output "Creo los registros para el alias"   
New-ItemProperty -Path $x86 -Name $AliasName -PropertyType String -Value $TCPAlias
New-ItemProperty -Path $x64 -Name $AliasName -PropertyType String -Value $TCPAlias
Write-Output "Se crearon los alias"

# Abro cliconfig para verificar el alias
Start-Process C:\Windows\System32\cliconfg.exe
Start-Process C:\Windows\SysWOW64\cliconfg.exe 

# 2 minutos para habilitar protocolos
Write-Output "Habilite los protocolos en cliconfig.Tiene 2 minutos para habilitarlos"   
Start-Sleep -s 30

########################################
# Se une el servidor a la granja
########################################

Write-Output "Conectando a la granja"

# Es recomendable que el front end tenga el host de distributed cache
Connect-SPConfigurationDatabase -DatabaseServer $serverDB -DatabaseName $dbConfig -Passphrase $s_configPassphrase -LocalServerRole Custom

# Verifico que la granja existe y esta corriendo. Si no, termino el script
$farm = Get-SPFarm
if (!$farm -or $farm.Status -ne "Online") {
    Write-Output "La Farm no se creo o no esta ejecutandose. Fin del script. Revise los logs en la carpeta Temp"
    exit
}
 
########################################
# Ejecuto tareas de configuracion de wizard
########################################
 
Write-Output "Instalando Help Collections"
Install-SPHelpCollection -All
 
Write-Output "Inicializando security"
Initialize-SPResourceSecurity
 
Write-Output "Instalando services"
Install-SPService
 
Write-Output "Registrando features"
Install-SPFeature -AllExistingFeatures
 
Write-Output "Instalando Application Content"
Install-SPApplicationContent

Write-Output "Inicio Time Service"
Start-Service SPTimerV4

Write-Output "Deshabilito LoopbackCheck"
New-ItemProperty HKLM:\System\CurrentControlSet\Control\Lsa -Name "DisableLoopbackCheck" -value "1" -PropertyType dword

########################################
#Start Central Administration
########################################
Write-Output "Iniciando Central Administration..."
& 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\BIN\psconfigui.exe' -cmd showcentraladmin

########################################
#Verifico el farm
########################################
Write-Output "Verifico la version del farm"
(get-spfarm).buildversion

Write-Output "Se unio correctamente correctamente el servidor a la granja !!!."

Parte 2–Sharepoint 2016 creando la granja

Indice de Instalación de Sharepoint 2016

Ingresar al Application Server “Custom” con una cuenta con privilegios de sysadmin sobre el SQL Server. Mi recomendación es ingresar con la cuenta de Farm para evitar problemas futuros.

Prueba la conexión al SQL Server, mediante un archivo .udl https://blogs.technet.microsoft.com/michaelgriswold/2014/01/06/the-easy-way-to-test-sql-connectivity/

image

image

Ejecuta una consola de PowerShell_ISE como ADMINISTRADOR

%windir%\system32\WindowsPowerShell\v1.0\PowerShell_ISE.exe

Recomendacion: agregar un break al inicio, e ir step by step ejecutando el script, así valida los valores en ejecución. En amarrillo algunas secciones importantes del script.

Para este script se definieron 3 cuentas de servicios, durante pasos posteriores se irán definiendo otras cuentas de servicio (Sharepoint SuperReader, Sharepoint SuperUser, Sharepoint Search Services, Sharepoint Claim-Kerberos, etc ):

  • svcspfarm: Sharepoint Server Farm Account, cuenta de identidad para el timer y central administration
  • svcspwapp: Sharepoint Web Application Account, cuenta de identidad para ejecutar los application pools del IIS
  • svcspsvcapps: Sharepoint Services Apps Account, cuenta de identidad para ejecutar los applications pools de los servicios.

Estas cuentas deben tener las siguientes local policies configuradas en cada servidor:

  • Adjust memory quotas for a process
  • Allow log on locally
  • Impersonate a client after authentication
  • Log on as a batch job
  • Log on as a service
  • Replace a process level token

Cuando te lance la pantalla de configuración de alias (x86, x64), habilita todos los protocolos

image

Descargar Script (validen los datos, tales como Host de SQL Server, cuentas, etc)

############################################################
#    Crear un farm de SharePoint 2016
#    Creado por Christian Azcon
############################################################
$ver = $host | select version
if ($ver.Version.Major -gt 1)  {$Host.Runspace.ThreadOptions = "ReuseThread"}
Add-PsSnapin Microsoft.SharePoint.PowerShell

########################################
# Defino Settings #
########################################

#SQL Alias
$AliasName = "SQLSP2016" 
# Cambia el nombre por el del SQL--> FQDN
$ServerName = "HostNameSQLServer.contoso.net"

$configPassphrase = 'SeguridadFraseSharepoint2016'

# Service accounts
$DOMAIN = "CONTOSO"

Write-Output "Defino las cuentas de usuario"
$accounts = @{}
$accounts.Add("svcspfarm", @{"username" = "svcspfarm"; "password" = 'xxxxxxxxxxx'})
$accounts.Add("svcspwapp", @{"username" = "svcspwapp"; "password" = 'xxxxxxxxxxx'})
$accounts.Add("svcspsvcapps", @{"username" = "svcspsvcapps"; "password" = 'xxxxxxxxxxx'})
 
Foreach ($account in $accounts.keys) {
    $accounts.$account.Add("credential", (New-Object System.Management.Automation.PSCredential ($DOMAIN + "\" + $accounts.$account.username),  (ConvertTo-SecureString -String $accounts.$account.password -AsPlainText -Force)))
}
Write-Output "Se inician las cuentas de usuario"

########################################
# Creo the SQL Alias
########################################

$x86 = "HKLM:\Software\Microsoft\MSSQLServer\Client\ConnectTo"
$x64 = "HKLM:\Software\Wow6432Node\Microsoft\MSSQLServer\Client\ConnectTo"
 
#Verifico si la clave ConnectTo ya existe, y la creo en caso contrario
if ((test-path -path $x86) -ne $True)
{
    write-host "$x86 no existe"
    New-Item $x86
}
if ((test-path -path $x64) -ne $True)
{
    write-host "$x64 no existe"
    New-Item $x64
}
 
#Defino el tipo de alias
$TCPAlias = ("DBMSSOCN," + $ServerName)
 
#Creo el TCP/IP Aliases
Write-Output "Creo los registros para el alias"   
New-ItemProperty -Path $x86 -Name $AliasName -PropertyType String -Value $TCPAlias
New-ItemProperty -Path $x64 -Name $AliasName -PropertyType String -Value $TCPAlias
Write-Output "Se crearon los alias"

# Abro cliconfig para verificar el alias
Start-Process C:\Windows\System32\cliconfg.exe
Start-Process C:\Windows\SysWOW64\cliconfg.exe 

# 30 segundos para habilitar protocolos
Write-Output "Habilite los protocolos en cliconfig"   
Start-Sleep -s 30

########################################
#    Inicio la configuracion de la granja
########################################

Write-Output "Inicio la configuracion de la granja"   
# Farm configuration
$s_configPassphrase = (ConvertTo-SecureString -String $configPassphrase -AsPlainText -force)
 
$serverDB = $AliasName
$dbConfig = "Sharepoint_Configuration"
$dbCentralAdmin = "Sharepoint_Content_CA"
 
$caPort = 9191
$caAuthProvider = "NTLM"
 
########################################
# Creo la granja
########################################

Write-Output "Creando la base de configuracion $dbConfig"

# Es recomendable que el front end tenga el host de distributed cache, por ello uso -skipRegisterAsDistributedCachehost $True
New-SPConfigurationDatabase -DatabaseName $dbConfig -DatabaseServer $serverDB -AdministrationContentDatabaseName $dbCentralAdmin -Passphrase  $s_configPassphrase -FarmCredentials $accounts.svcspfarm.credential -skipRegisterAsDistributedCachehost $True -LocalServerRole Custom


# Verifico que la granja existe y esta corriendo. Si no, termino el script
$farm = Get-SPFarm
if (!$farm -or $farm.Status -ne "Online") {
    Write-Output "La Farm no se creo o no esta ejecutandose. Fin del script. Revise los logs en la carpeta Temp"
    exit
}
 
Write-Output "Creando el site de Central Administration en el puerto $caPort"
New-SPCentralAdministration -Port $caPort -WindowsAuthProvider $caAuthProvider
 
Write-Output "Se creo correctamente el Central Administration"
 
########################################
# Ejecuto tareas de configuracion de wizard
########################################
 
Write-Output "Instalando Help Collections"
Install-SPHelpCollection -All
 
Write-Output "Inicializando security"
Initialize-SPResourceSecurity
 
Write-Output "Instalando services"
Install-SPService
 
Write-Output "Registrando features"
Install-SPFeature -AllExistingFeatures
 
Write-Output "Instalando Application Content"
Install-SPApplicationContent
 
########################################
# Add managed accounts
########################################

Write-Output "Creando managed accounts ..."
#New-SPManagedAccount -credential $accounts.svcspfarm.credential Ya se agrega sola cuando se crea la granja
New-SPManagedAccount -credential $accounts.svcspwapp.credential
New-SPManagedAccount -credential $accounts.svcspsvcapps.credential

########################################
#Start Central Administration
########################################
Write-Output "Iniciando Central Administration..."
& 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\BIN\psconfigui.exe' -cmd showcentraladmin

########################################
#Verifico el farm
########################################
Write-Output "Verifico la version del farm"
(get-spfarm).buildversion

Write-Output "Se completo el build del Farm correctamente!!!."

Sharepoint 2016 Installation

Voy a realizar un par de posts sobre la instalación de Sharepoint 2016. Algunos detalles iniciales, cómo la instalación de Windows Servers y SQL Server, los voy a excluir, pero si estaré realizando algún post sobre best practices sobre Windows Server y SQL Server (las cuales pueden variar de acuerdo a sus ambientes)

A partir de Sharepoint 2016, tenemos un nuevo concepto llamado “MinRole”, al usar este tipo de deployment, el administrador de la granja puede definir un role por cada servidor, y Sharepoint automáticamente configurará los servicios en cada servidor basado en el role elegido, optimizando la performance de la plataforma. Para mayor información puede consultar el siguiente link: https://technet.microsoft.com/en-us/library/mt346114(v=office.16).aspx

Hay 5 tipos de configuraciones:

Custom: Reservado para servicios aislados de otros servicios, Ej: Performance Point, 3rd applications, etc

Web Front End: Configuración optimizada para baja latencia hacia el usuario final

Single Server Farm: Provisiona todos los servicios en un sólo servidor, es para fines de desarrollo o de evaluación

Search: Reservado para funciones de search.

Application: Servicios optimizados para alto througput, tales como jobs, o request con alto volumen que corren de fondo.

Distributed Cache: Servicios de cache distribuida para la granja.

 

Sharepoint 2016 Min Role – Cantidad mínima de servidores para una granja funcional (5)

image 

Para esta instalación sólo usaré 3 servidores, una topología clásica, ya que para utilizar MinRole debes tener 5 servers. Tanto el WebFront End y Application Server tendrá un rol “custom”.

image

Algunas definiciones:

  • El custom WebFront End tendrá el host de Cache Distributed
  • Se usará SQL Server 2014 SP2
  • El central administration estará en el Application Server “Custom”, y será este servidor el primero en instalar.

Parte 1 - Sharepoint 2016 GA Installation - Prerequisites Installer

Parte 2 - Creando la granja de Sharepoint

Parte 3 – Conectando el WebFront End a la granja

Parte 4 – Creando Sharepoint Web Services Default Application Pool

Parte 5 - Creación de Usage and Health Data Collection Service

Parte 6 – Creación de web application

Parte 7 – Creación del Search Service

Sharepoint 2016 GA Installation - Prerequisites Installer– Parte 1

Indice de Instalación de Sharepoint 2016

Los prerequisitos de Sharepoint 2016 GA son los siguientes:

 

IMPORTANTE: cuando bajes los archivos de internet, verifica que no esté bloqueado el archivo. Principalmente  Microsoft WCF Data Services 5.6

image

Para saber los prerrequisitos puedes ejecutar el siguiente comando:  prerequisiteinstaller.exe /?

image

Script para instalar los prerequisitos: se supone que la imagen de Sharepoint (.iso) está montada en la partición E:\

Primer ejecutar: Set-ExecutionPolicy -ExecutionPolicy Unrestricted

IMPORTANTE: ejecutar la parte de Start-Process en una línea completa

$SharePoint2016Path = "D:\Prods\SP2016-Prerequisites"
 
Start-Process "E:\PrerequisiteInstaller.exe" –ArgumentList "/SQLNCli:$SharePoint2016Path\sqlncli.msi /Sync:D:\Prods\SP2016-Prerequisites\Synchronization.msi /AppFabric:$SharePoint2016Path\WindowsServerAppFabricSetup_x64.exe /IDFX11:$SharePoint2016Path\MicrosoftIdentityExtensions-64.msi /MSIPCClient:$SharePoint2016Path\setup_msipc_x64.exe /KB3092423:$SharePoint2016Path\AppFabric-KB3092423-x64-ENU.exe /WCFDataServices56:$SharePoint2016Path\WcfDataServices56.exe /ODBC:$SharePoint2016Path\msodbcsql.msi /DotNetFx:$SharePoint2016Path\NDP46-KB3045557-x86-x64-AllOS-ENU.exe /MSVCRT11:$SharePoint2016Path\vcredist_x64.exe /MSVCRT14:$SharePoint2016Path\vc_redist.x64.exe"

Descargar script de powershell

image

 

Una vez instalado los prerequisitos, puedes instalar los binarios de Sharepoint 2016

image

image

IMPORTANTE: una vez instalado no lanzar el configuration Wizard.

 

ERROR EN LA INSTALACION PARA TENER EN CUENTA

Al instalarlo por powershell o por GUI, me lanzaba el siguiente error. Era porque cuando se bajó Microsoft WCF Data Services 5.6, había quedado bloqueado por Windows.

image

Joining Farm failed. The exception type is Microsoft.SharePoint.Upgrade.SPUpgradeException The exception is One or more types failed to load

image

Joining Farm failed. The exception type is Microsoft.SharePoint.Upgrade.SPUpgradeException The exception is One or more types failed to load. Please refer to the upgrade log for more details. StackTrace is    at Microsoft.SharePoint.Upgrade.SPActionSequence.LoadUpgradeActions()     at Microsoft.SharePoint.Upgrade.SPActionSequence.get_Actions()     at Microsoft.SharePoint.Upgrade.SPActionSequence.get_ActionsInternal()     at Microsoft.SharePoint.Upgrade.SPUtility.GetLatestTargetSchemaVersionBeforeMajorVersion(Type typeActionSequence, Int32 majorVer)     at Microsoft.SharePoint.Upgrade.SPSiteSequence.get_PreviousTargetSchemaVersion()     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.PopulateSequencesTable(StringBuilder sqlstr, Boolean siteSequence)     at Microsoft.SharePoint.Upgrade.SPUp...    
07/13/2016 08:53:16.30*    psconfigui.exe (0x11B8)                     0x0954    SharePoint Foundation             Topology                          aj4j4    Unexpected    ...gradeSession.ConstructSiteNeedsUpgradeQuery(Guid siteId)     at Microsoft.SharePoint.Upgrade.SPContentDatabaseSequence.GetSiteNeedsUpgrade(SPUpgradeSession session, SPContentDatabase database, Dictionary`2& dictSitesNeedUpgrade, Dictionary`2& dictSitesNeedFeatureUpgrade)     at Microsoft.SharePoint.Upgrade.SPContentDatabaseSequence.AddNextLevelObjects()     at Microsoft.SharePoint.Upgrade.SPHierarchyManager.Grow(SPTree`1 root, Boolean bRecursing, SPDelegateManager delegateManager)     at Microsoft.SharePoint.Upgrade.SPHierarchyManager.Grow(SPTree`1 root, SPDelegateManager delegateManager)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.NeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.ReflexiveNeedsUpgrade(Object o, Boolean bRecurse)     at ...    
07/13/2016 08:53:16.30*    psconfigui.exe (0x11B8)                     0x0954    SharePoint Foundation             Topology                          aj4j4    Unexpected    ...Microsoft.SharePoint.Upgrade.SPUpgradeSession.NeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.ReflexiveNeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.NeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.ReflexiveNeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.NeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.ReflexiveNeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.NeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Administration.SPServerProductInfo.DetectLocalUpgradeStatus()     at Microsoft.SharePoint.Admi...    
07/13/2016 08:53:16.30*    psconfigui.exe (0x11B8)                     0x0954    SharePoint Foundation             Topology                          aj4j4    Unexpected    ...nistration.SPServerProductInfo.DetectLocalProductVersions(SPProductVersions prodVer)     at Microsoft.SharePoint.Administration.SPServerProductInfo.UpdateProductInfoInDatabase(Guid serverGuid)     at Microsoft.SharePoint.Administration.SPFarm.Join(Boolean skipRegisterAsDistributedCacheHost, Nullable`1 serverRole)    
07/13/2016 08:53:16.30     psconfigui.exe (0x11B8)   

 

SharePoint Foundation Upgrade SPSiteWssSequence ajywy ERROR Exception: Could not load file or assembly 'Microsoft.Data.Edm, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. 00000000-0000-0000-0000-000000000000    

SharePoint Foundation Upgrade SPSiteWssSequence ajywy ERROR Exception: Could not load file or assembly 'Microsoft.Data.OData, Version=5.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. 00000000-0000-0000-0000-000000000000    
07/13/2016 08:53:16.30     psconfigui.exe (0x11B8)                     0x0954    SharePoint Foundation             Topology                          aj4j4    Unexpected    Joining Farm failed. The exception type is Microsoft.SharePoint.Upgrade.SPUpgradeException The exception is One or more types failed to load. Please refer to the upgrade log for more details. StackTrace is    at Microsoft.SharePoint.Upgrade.SPActionSequence.LoadUpgradeActions()     at Microsoft.SharePoint.Upgrade.SPActionSequence.get_Actions()     at Microsoft.SharePoint.Upgrade.SPActionSequence.get_ActionsInternal()     at Microsoft.SharePoint.Upgrade.SPUtility.GetLatestTargetSchemaVersionBeforeMajorVersion(Type typeActionSequence, Int32 majorVer)     at Microsoft.SharePoint.Upgrade.SPSiteSequence.get_PreviousTargetSchemaVersion()     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.PopulateSequencesTable(StringBuilder sqlstr, Boolean siteSequence)     at Microsoft.SharePoint.Upgrade.SPUp...    
07/13/2016 08:53:16.30*    psconfigui.exe (0x11B8)                     0x0954    SharePoint Foundation             Topology                          aj4j4    Unexpected    ...gradeSession.ConstructSiteNeedsUpgradeQuery(Guid siteId)     at Microsoft.SharePoint.Upgrade.SPContentDatabaseSequence.GetSiteNeedsUpgrade(SPUpgradeSession session, SPContentDatabase database, Dictionary`2& dictSitesNeedUpgrade, Dictionary`2& dictSitesNeedFeatureUpgrade)     at Microsoft.SharePoint.Upgrade.SPContentDatabaseSequence.AddNextLevelObjects()     at Microsoft.SharePoint.Upgrade.SPHierarchyManager.Grow(SPTree`1 root, Boolean bRecursing, SPDelegateManager delegateManager)     at Microsoft.SharePoint.Upgrade.SPHierarchyManager.Grow(SPTree`1 root, SPDelegateManager delegateManager)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.NeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.ReflexiveNeedsUpgrade(Object o, Boolean bRecurse)     at ...    
07/13/2016 08:53:16.30*    psconfigui.exe (0x11B8)                     0x0954    SharePoint Foundation             Topology                          aj4j4    Unexpected    ...Microsoft.SharePoint.Upgrade.SPUpgradeSession.NeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.ReflexiveNeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.NeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.ReflexiveNeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.NeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.ReflexiveNeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Upgrade.SPUpgradeSession.NeedsUpgrade(Object o, Boolean bRecurse)     at Microsoft.SharePoint.Administration.SPServerProductInfo.DetectLocalUpgradeStatus()     at Microsoft.SharePoint.Admi...    
07/13/2016 08:53:16.30*    psconfigui.exe (0x11B8)                     0x0954    SharePoint Foundation             Topology                          aj4j4    Unexpected    ...nistration.SPServerProductInfo.DetectLocalProductVersions(SPProductVersions prodVer)     at Microsoft.SharePoint.Administration.SPServerProductInfo.UpdateProductInfoInDatabase(Guid serverGuid)     at Microsoft.SharePoint.Administration.SPFarm.Join(Boolean skipRegisterAsDistributedCacheHost, Nullable`1 serverRole)    
07/13/2016 08:53:16.30     psconfigui.exe (0x11B8)                     0x0954    SharePoint Foundation             Topology                          88ah    High        Unjoining the farm.    
07/13/2016 08:53:16.30     psconfigui.exe (0x11B8)                     0x0954    SharePoint Foundation             Topology                          7f7z    Medium      Attempting to unprovision the  instance of the  service.    
07/13/2016 08:53:16.32     psconfigui.exe (0x11B8)                     0x0954    SharePoint Foundation             Config Cache                      8xqz    Medium      Updating SPPersistedObject SPUsageServiceInstance. Version: 3285 Ensure: False, SkipObjectCallbackCheck: False, HashCode: 66389619, Id: 32642bdc-4d98-44c3-a772-c41b85fdd60f, Stack:    at Microsoft.SharePoint.Administration.SPPersistedObject.BaseUpdateCore(Boolean legacyUpdate)     at Microsoft.SharePoint.Administration.SPPersistedObject.Update()     at Microsoft.SharePoint.Administration.SPServer.Unprovision()     at Microsoft.SharePoint.Administration.SPFarm.Unjoin()     at Microsoft.SharePoint.Administration.SPFarm.Join(Boolean skipRegisterAsDistributedCacheHost, Nullable`1 serverRole)     at Microsoft.SharePoint.PostSetupConfiguration.ConfigurationDatabaseTask.CreateOrConnectConfigDb()     at Microsoft.SharePoint.PostSetupConfiguration.ConfigurationDatabaseTask.Run()     at Microsoft.Sh...    
07/13/2016 08:53:16.32*    psconfigui.exe (0x11B8)                     0x0954    SharePoint Foundation             Config Cache                      8xqz    Medium      ...arePoint.PostSetupConfiguration.TaskThread.ExecuteTask()     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)     at System.Threading.ThreadHelper.ThreadStart()