Wednesday, December 26, 2012

Object DB2 (previous name: DB1) failed in event OnRestore

Hi,


I got the below error after restoring the Farm backup though I had provided the correct username and password.

Object DB2 (previous name: DB1) failed in event OnRestore

In the sprestore log I got the error as below

sprestore log error
[12/12/2012 2:38:05 PM] FatalError: Object DB2 (previous name: DB1) failed in event OnPostRestore. For more information, see the spbackup.log or sprestore.log file located in the backup directory.
                SPException: Cannot attach database to Web application. Use the command line tool or Central Administration pages to attach the database manually to the proper Web Application.
We couldn’t get the reason for occurring this error.
But we noticed that particular DB has not been restored and it’s throwing an error while restoring.

So the workaround is we had added DB name through ‘Manage Content databases’ in Central Administration as below
 Select the appropriate web application before adding the content database as below
Enter Database server/Alias Name, Database Name that has been failed after Restoring the database as below. Click Ok
After this we were able to browse the site without any issues.

Tuesday, November 13, 2012

Operation is not valid due to the current state of the object


Hi,

After clicking ‘Start Restore’ while restoring farm, sometimes we get the error as below.
Finally our architect has come up with the solution to clear the roadblock i.e.

Added key to increase value of Maximum Http Collection as below
Post this farm restore went fine. This error comes up if farm back up size is heavy.


Monday, October 29, 2012

SP1 Upgrade in SharePoint 2010


Hi,

In SharePoint 2010, SP1 is required where some features are well performed.
For example in the absence of SP1,user profiles will not be imported.
Below is the sequence that has been followed to upgrade SP1

Step 1:
Run sharepointfoundation2010sp1-kb2460058-x64-fullfile-en-us.exe

Step 2:
Run spflanguagepack2010sp1-kb2460059-x64-fullfile-de-de.exe
Run spflanguagepack2010sp1-kb2460059-x64-fullfile-es-es.exe
Run spflanguagepack2010sp1-kb2460059-x64-fullfile-fr-fr.exe
Run spflanguagepack2010sp1-kb2460059-x64-fullfile-it-it.exe
Run spflanguagepack2010sp1-kb2460059-x64-fullfile-ja-jp.exe
Run spflanguagepack2010sp1-kb2460059-x64-fullfile-ko-kr.exe
Run spflanguagepack2010sp1-kb2460059-x64-fullfile-nl-nl.exe
Run spflanguagepack2010sp1-kb2460059-x64-fullfile-pt-pt.exe
Run spflanguagepack2010sp1-kb2460059-x64-fullfile-ru-ru.exe
Run spflanguagepack2010sp1-kb2460059-x64-fullfile-sv-se.exe
Run spflanguagepack2010sp1-kb2460059-x64-fullfile-tr-tr.exe
Run spflanguagepack2010sp1-kb2460059-x64-fullfile-zh-cn.exe

Step 3:
Run officeserver2010sp1-kb2460045-x64-fullfile-en-us.exe

Step 4:
Run serverlanguagepack2010sp1-kb2460056-x64-fullfile-de-de.exe
Run serverlanguagepack2010sp1-kb2460056-x64-fullfile-es-es.exe
Run serverlanguagepack2010sp1-kb2460056-x64-fullfile-fr-fr.exe
Run serverlanguagepack2010sp1-kb2460056-x64-fullfile-it-it.exe
Run serverlanguagepack2010sp1-kb2460056-x64-fullfile-ja-jp.exe
Run serverlanguagepack2010sp1-kb2460056-x64-fullfile-ko-kr.exe
Run serverlanguagepack2010sp1-kb2460056-x64-fullfile-nl-nl.exe
Run serverlanguagepack2010sp1-kb2460056-x64-fullfile-pt-pt.exe
Run serverlanguagepack2010sp1-kb2460056-x64-fullfile-ru-ru.exe
Run serverlanguagepack2010sp1-kb2460056-x64-fullfile-sv-se.exe
Run serverlanguagepack2010sp1-kb2460056-x64-fullfile-tr-tr.exe
Run serverlanguagepack2010sp1-kb2460056-x64-fullfile-zh-cn.exe

Cumulative updates of august 2012
Run office2010-kb2687353-fullfile-x64-glb.exe

Now after installing the above as per the sequence, now faced issue as below while running the Cumulative updates of august 2012
Remedy for this issue is go to control panel->Uninstall Program

You will be able to see the list of language packs that have been installed as below.

Each language pack has version(marked in blue) as below

Now if you notice that any language pack version number is different, then reinstall that language pack from step 2,step 4
For me Turkish language pack was not getting installed used below command to install the same.
"E:\SP1 for SP2010\Step 4 - Service Pack 1 for Server Language Pack 2010 (KB2460056)\serverlanguagepack2010sp1-kb2460056-x64-fullfile-tr-tr.exe"PACKAGE.BYPASS.DETECTION.CHECK=1

Post this cumulative updates of August 2012 installation went fine.

Note:
1)Central Administration was not opening because till whole installation gets complete, central administration might not open
2)After installation run SharePoint 2010 configuration wizard one by one in all the servers of the farm
3)Cumulative updates of August 2012 takes some time i.e. minimum 4 hours, maximum 8 hours. Till that time please be patientJ

Wednesday, August 29, 2012

Install/Uninstall PowerPivot 2010


Hi,

Below are the commands that needs to be executed for Installation/Un installation of Power Pivot 2010
These commands needs to be run in command prompt
Installation
"E:\SQL2008R2\setup.exe" /ACTION="Install"

Un Installation
"E:\SQL2008R2\setup.exe" /ACTION="UnInstall"

Thursday, August 23, 2012

New version of workflow not created after deployment


Hi,

We were facing an issue while deploying a custom list workflow, designed using SharePoint Designer 2010.
After deployment, a new version of the workflow was not being created. I can see that the changes I have made earlier are reflecting in the existing workflow.
Below are the steps I followed to get the job done (which of course is not working)

1.       Opened the existing workflow using SPD  and clicked on Edit Workflow.
2.       After making changes to the Tasks, I saved the workflow as a template (a wsp).
3.       Deployed the solution to the Solution Gallery and activated it.
4.       Activated the feature created at the Site Level.
When I check the workflows associated with the list, it still shows a single workflow. When I open the workflow again using Designer, it shows the changes that I have made earlier.
I am not sure what is going wrong here. There are a few things that I have noticed. After making changes to the tasks, the forms associated with the workflow change their status as (Needs Update). I opened these forms in InfoPath Designer, which shows that some fields have been added/modified and the form needs to be updated with the list of available fields. Later I publish the form to the server. Even then, I don’t see any changes in the Task form status in SPD. This is also a custom task form that we have designed.

Fix
We have found out the issue. When we tried to publish the workflow to the same site collection, we got an error. So we had to republish it several times before saving it as a template. When this solution was deployed to a different site collection, we were not able to see any new workflow association. 

The issue was with the xoml configuration file where the visibility property of the workflow was set to "DraftPublic" as opposed to the "Public" seen for normal published workflows. So we required to use designer to change this value in the workflow manually and then save it as a template

Error running configuration wizard during sp1 up gradation



Hi,

We have installed the latest Cumulative Updates (April 2012 version) on SharePoint Server 2010 farm. We installed both the Foundation and Server hot fix package on all application servers and then the web front end.
Next step was running the SharePoint 2010 Products Configuration Wizard on the application server. The wizard started out just fine, but in step 9 (“The farm is being upgraded in the timer service process. The task is  41.23% completed.”) where it subsequently failed (Configuration failed). 

 The error message was:
An exception of type Microsoft.SharePoint.PostSetupConfiguration.PostSetupConfigurationTaskException was thrown.  Additional exception information: Failed to upgrade SharePoint Products.”


Reading in the logs revealed what seemed to be why the upgrade failed, but no hint on how to fix it:
01/04/2011 15:27:39  14  INF                    Resource id to be retrieved is UpgradeTaskFailConfigSyncDisplayLabel for language English (United States)
01/04/2011 15:27:39  14  INF                    Resource retrieved id UpgradeTaskFailConfigSyncDisplayLabel is Failed to upgrade SharePoint Products.
01/04/2011 15:27:39  14  INF                  Leaving function StringResourceManager.GetResourceString
01/04/2011 15:27:39  14  INF                  Entering function Common.BuildExceptionMessage
01/04/2011 15:27:39  14  INF                    Entering function StringResourceManager.GetResourceString
01/04/2011 15:27:39  14  INF                      Resource id to be retrieved is ExceptionInfo for language English (United States)
01/04/2011 15:27:39  14  INF                      Resource retrieved id ExceptionInfo is An exception of type {0} was thrown.  Additional exception information: {1}

After googling our teammate has found fix for this issue as below.

Fix:  While troubleshooting the issue, we found out that the database was running out of space. We increased the space of the database. Even then the issue wasn’t resolved. We had to run a Power Shell as found in the below article. This fixed the issue and we were able to complete the Configuration Wizard.

Below is the reference link which helped us in resolving this issue.

Monday, August 20, 2012

Search Center Site Collection using powershell


Hi,

Our Requirement was to create site collection for Search Center.

One more important expectation is once Search Center site collection gets created, two pages are to be created under Pages Library.

Those two pages are "Advanced.aspx" and "Results.aspx".

Respective web parts  needs to available on those pages i.e.

Advanced Search Box web part should be available on "Advanced.aspx"
Search Core Results web part should be available on "Results.aspx"

For that below is the script that has been executed

// CreateSiteCollections.ps1
# Automates creation of site collections based on information stored in a XML file.

# This method returns the directory of the script
$0 = $MyInvocation.MyCommand.Definition          
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$RootPath = $dp0 | split-path 


## Get XML configuration file parameters
[string]$InputFile = $("$RootPath\SiteCollectionScripts\WPSiteCollectionsInputs.xml")   

$xmlinput = [xml] (get-content $InputFile)
$item = $xmlinput.SiteCollectionConfig


#Region Create site collection in the web application, if the site collection exsits then return the existed site collection
#otherwise create a new site collection  
Function CreateSiteCollection($name,$url, $description,$webApplication,$ownerAlias, $secondaryOwnerAlias,$contentdatabase,$Template,$LCID)
{
    Try
    {
        Write-Host -ForegroundColor White "- Start to create the Site Collection: `"$name`"..."
        #$sc = get-spsite -identity $url | Out-Null
        $sc = get-spsite -limit all | Where-Object {$_.Url -eq $url}
        if($sc -eq $null)
        {

            $cntDB = get-spcontentdatabase -webapplication $webApplication | where-object {$_.name -eq $contentdatabase}
            if($cntDB -eq $null)
            {
                $cntDB = new-spcontentdatabase -name $contentdatabase -webapplication $webApplication
            }

            $sc = New-SPSite -Url $url -OwnerAlias $ownerAlias -SecondaryOwnerAlias $secondaryOwnerAlias -ContentDatabase $contentdatabase -Description $description -Name $name -Template $Template -Language $LCID
           
            #Add NT Authority/Authenticated users to Search Center and Site Provisioning Application         
          
            if($name -eq "SearchCenter")
            {
                New-SPUser -UserAlias "NT AUTHORITY\authenticated users" -web $url -PermissionLevel Contribute
               
                #add the search center site collection to the current subscription
                $sub = get-spsitesubscription    
                set-spsite -identity $sc -sitesubscription $sub

            }
        }
        else
        {
            Write-Host -ForegroundColor White "- Site collection: `"$name`" already exists, continuing..."
        }
    }
    catch
    {
        Write-Host $_
    }
}
#EndRegion


#Get the Web Application Details

$ContentPortalName = $item.ContentPortalName


$GetSPWebApplication = Get-SPWebApplication $ContentPortalName
    If ($GetSPWebApplication -eq $Null)
        {

            Write-Warning " - Web application does not exist"
            Write-Warning " - Check if the Web Application has been created or not"
            break
        }
    else
                {
            $WebApp = Get-SpWebApplication $ContentPortalName
                }


$scs = $item.selectnodes("SPSiteCollection")
foreach($sc in $scs)
{
    $name = $sc.Name 
    $scUrl = $WebApp.URL+$sc.ManagedPath
    CreateSiteCollection -name $sc.Name -url $scUrl -description $sc.Description -webApplication $WebApp -ownerAlias $sc.OwnerAlias -secondaryOwnerAlias "$env:USERDOMAIN\$env:USERNAME" -contentdatabase $sc.ContentDatabase -Template $sc.Template -LCID $sc.LCID
    Write-Host -ForegroundColor White "- The site collection: $name has been created"

               
}
// WPSiteCollectionsInputs.xml
<?xml version="1.0" ?>
<SiteCollectionConfig>
                <ContentPortalName>http://webappurl</ContentPortalName>            
                <SPSiteCollection>
                                <Name>SearchCenter</Name>
                                <Description>Enterprise Search Center Site</Description>
                                <ManagedPath>sites/SearchCenter</ManagedPath>
                                <ContentDatabase>dbname</ContentDatabase>
                                <Template>SRCHCEN#0</Template>
                                <LCID>1033</LCID>
                                <OwnerAlias>domain\username</OwnerAlias>
                                <SecondaryOwnerAlias> domain\username</SecondaryOwnerAlias>
                </SPSiteCollection>
</SiteCollectionConfig>

Finally I got the result as below

Installing PDF Filter with Powershell


Hi,

Recently we have worked on installing PDF Filter with the power shell.
Along with the script, PDFFilter64installer, pdf16 image was copied in the same folder.
Below is the code as below

//PDFFilterInstall_Batch.bat
Powershell.exe -Command Set-ExecutionPolicy "Bypass"
Powershell.exe -Command "& {E:\PDFFilter\PDFFilterScript.ps1}"
Pause

// PDFFilterScript.ps1
Add-PSSnapin "Microsoft.SharePoint.PowerShell"

$0 = $MyInvocation.MyCommand.Definition                 # Get complete file path (eg:  E:\SP2010AppServer\SetupInputs.xml)
$dp0 = [System.IO.Path]::GetDirectoryName($0)           # Get current Directory  file path  (eg:  E:\SP2010AppServer)
$bits = Get-Item $dp0 | Split-Path -Parent              # Get current Drive   (eg:  E:\)

function InstallPDFFilter()
{
                $installationPackagePath = $dp0
                $installationPackageFileName = "PDFFilter64installer.msi"
                $logoFileName = "pdf16.gif"   
    $searchServiceApplication = "EnterPrise Search Service Application"
    $filterFile = "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML\DOCICON.XML"
    $filterIconPath = "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\IMAGES\"

    #Install PDF iFilter package
    Write-Host -ForegroundColor White "- Installing PDF Filter..."
    try
    {
        Start-Process "$installationPackagePath\$installationPackageFileName" -ArgumentList "/passive /norestart" -WindowStyle Minimized -Wait
        If (-not $?) {throw}
    }
    catch
    {
        Write-Host -ForegroundColor Red "- Error: $LastExitCode"
                                If ($LastExitCode -eq "1") {throw "- Another instance of this application is already running"}
                                ElseIf ($LastExitCode -eq "2") {throw "- Invalid command line parameter(s)"}
                                ElseIf ($LastExitCode -eq "1001") {throw "- A pending restart blocks installation"}
                                ElseIf ($LastExitCode -eq "3010") {throw "- A restart is needed"}
                                Else {throw "- An unknown error occurred installing package"}
    }
    Write-Host -ForegroundColor White "- PDF Filter installed successfully"
    #Copy logo file to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\IMAGES\
    Copy-Item "$installationPackagePath\$logoFileName" -destination $filterIconPath

    #Write mapping entry to the DOCICON.xml file under C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\XML
   
    Write-Host -ForegroundColor White " - Adding pdfs as extension to docicons xml file" 
    # Load XML from file:
    $xmldata = [xml](Get-Content $filterFile)
    $xpath="Mapping[@Key='pdf']"
    $pdfMapping = $xmldata.DocIcons.ByExtension.SelectSingleNode($xpath)
    if($pdfMapping -eq $null -or $pdfMapping -eq "")
    {
        # Create new node:
        $pdfMapping = $xmldata.CreateElement("Mapping")
        $pdfMapping.SetAttribute("Key","pdf")
        $pdfMapping.SetAttribute("Value",$logoFileName)
        # Write nodes in XML:
        $xmldata.DocIcons.ByExtension.AppendChild($pdfMapping)
        $xmldata.Save($filterFile)
    }
    Write-Host -ForegroundColor White " - XML updated."
   
    #add file type to search service application
   
    Write-Host -ForegroundColor White "Adding PDF to the list of search crawl extensions in the Search Appliation..."
    $searchapp = Get-SPEnterpriseSearchServiceApplication $searchServiceApplication
    $pdfExtension = Get-SPEnterpriseSearchCrawlExtension "pdf" -SearchApplication $searchApp -ErrorVariable err -ErrorAction "SilentlyContinue"
   
    if($pdfExtension -eq $null)
    {
        $searchapp | New-SPEnterpriseSearchCrawlExtension "pdf"
        Write-Host -ForegroundColor White " - Adding PDF extension completed."
    }
    else
    {
        Write-Host -ForegroundColor White " - The PDF extension was already in the list"
    }
   
    Write-Host -ForegroundColor White " - Adding pdf entries for Sharepoint PDF Search in the registry..."
    # if (-not $(Test-Path -Path $InputFile -Type Leaf))
    if (-not $(Test-Path "HKLM:\SOFTWARE\Microsoft\Office Server\14.0\Search\Setup\Filters\.pdf"))
    {
        New-Item -path registry::'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\14.0\Search\Setup\Filters\.pdf' | Out-Null
        New-ItemProperty -Path registry::'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\14.0\Search\Setup\Filters\.pdf' -Name "Extension" -value ".pdf" -PropertyType string  | Out-Null
        New-ItemProperty -Path registry::'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\14.0\Search\Setup\Filters\.pdf' -Name "Mime Types" -value "application/pdf" -PropertyType string  | Out-Null
        New-ItemProperty -Path registry::'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\14.0\Search\Setup\Filters\.pdf' -Name "FileTypeBucket" -value "1" -PropertyType dword  | Out-Null
    }
    if (-not $(Test-Path "HKLM:\SOFTWARE\Microsoft\Office Server\14.0\Search\Setup\ContentIndexCommon\Filters\Extension\.pdf"))
    {
        New-Item -Path registry::'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\14.0\Search\Setup\ContentIndexCommon\Filters\Extension\.pdf' | Out-Null
        New-ItemProperty -Path registry::'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office Server\14.0\Search\Setup\ContentIndexCommon\Filters\Extension\.pdf' -name "(Default)" -Value "{E8978DA6-047F-4E3D-9C78-CDBE46041603}" -PropertyType string | Out-Null
    }
   
   
    #Restart services
    Write-Host -ForegroundColor White "- Restart SharePoint Timer Service..."
    IISReset
    restart-service SPTimerV4
    Write-Host -ForegroundColor White "- Timer Service restarted successfully"
}

InstallPDFFilter

Finally after executing the script you can see the PDF icon in the crawl extensions as below

Search Topology Automation using Powershell



Hi,

Search Topology automation has been done using power shell script.
Below is the sequence that has been followed for search topology.

1)      Creating Managed Account
2)      Creating Application Pool
3)      Creating Search Service Application
4)      Creating Service Proxy
5)      Creating Crawl Topology(crawl components0,1 in app server2, crawl components2,3 in app server3)
6)      Creating Query Topology(query components0,2 in WFE server2, query components 1,3 in WFE server3)
7)      Configure Default Content Access Account
8)      Configure Crawl Target Server
The script is as below

//SearchTopology_Batch.bat
Powershell.exe -Command Set-ExecutionPolicy "Bypass"
Powershell.exe -Command "& {D:\Naga\SP2010AppServer\SearchTopologyAutomation\SearchTopologyScript.ps1}"
Pause

//SearchTopologyScript.ps1
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{
Write-Host "Loading SharePoint Powershell Snap-in"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}

# Get complete file path (eg:  E:\SP2010AppServer\xxxx.ps1)
$filepath = $MyInvocation.MyCommand.Definition                                        
# Get current Directory  file path  (eg:  E:\SP2010AppServer)
$directorypath = [System.IO.Path]::GetDirectoryName($filepath)         
# Get current Drive   (eg:  E:\)
$directory = Get-Item $directorypath | Split-Path -Parent              
$InputFile = $directorypath+"\SetupInputs.xml"

$xmlinput = [xml] (get-content $InputFile)
$item = $xmlinput.SearchTopologyInputs


## Start logging
$LogTime = Get-Date -Format yyyy-MM-dd_h-mm
$LogFile = $directorypath + "\SearchTopologyScript-$LogTime.rtf"
Start-Transcript -Path $LogFile -Force


#Region Register Managed Accounts

$ManagedAcctUserName = $item.ManagedAccountName

If (($item.ManagedAccountPassword -ne "") -and ($item.ManagedAccountPassword -ne $null))
{$ManagedAcctPassword = (ConvertTo-SecureString $item.ManagedAccountPassword -AsPlainText -force)}

$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $ManagedAcctUserName,$ManagedAcctPassword

New-SPManagedAccount –Credential $credentials
#EndRegion

$ContentAccessAcctName = $item.DefaultContentAccessAcctName
If (($item.DefaultContentAccessAcctPassword -ne "") -and ($item.DefaultContentAccessAcctPassword -ne $null))
{$ContentAccessAcctPassword = (ConvertTo-SecureString $item.DefaultContentAccessAcctPassword -AsPlainText -force)}

##$ContentAccessAcctPassword = $item.DefaultContentAccessAcctPassword


#---------------------Variables-----------------------------------#
##$SearchAppPoolName - to get Search Application Pool Name from xml
$SearchAppPoolName = $item.SearchAppPoolName

##$searchserviceapp- to get Search Service Application Name from xml
$searchserviceappname = $item.SearchServiceApplicationName

##$SearchServiceAppProxy - to get Search Service Application Proxy from xml
$SearchServiceAppProxy = $item.SearchServiceApplicationProxy

##$SearchAppProxyName - to get Search Application Proxy Name from xml
$SearchAppProxyName = $item.SearchServiceApplicationProxyName

##$SearchServiceAppName - to get Search Service Application Name from xml
$SearchServiceAppName = $item.SearchServiceApplicationName

##App2servernamefromxml - to get App 2 server Name from xml
$App2servernamefromxml =  $item.App2servername

##App3servernamefromxml - to get App 3 server Name from xml
$App3servernamefromxml =  $item.App3servername

##wfe1servernamefromxml - to get wfe 1 server Name from xml
$wfe1servernamefromxml = $item.wfe1servername

##wfe2servernamefromxml - to get wfe 2 server Name from xml
$wfe2servernamefromxml = $item.wfe2servername

##wfe3servernamefromxml - to get wfe 3 server Name from xml
$wfe3servernamefromxml = $item.wfe3servername


##db1servernamefromxml - to get db1 server Name from xml
$db1servernamefromxml = $item.DBServer1

##db2servernamefromxml - to get db2 server Name from xml
$db2servernamefromxml = $item.DBServer2

##db3servernamefromxml - to get db3 server Name from xml
$db3servernamefromxml = $item.DBServer3

##$crawlDatabaseName - to create new database for crawl
$crawlDatabaseName = $item.CrawlDatabase

##$propertydatabasename - to create new database for property
$propertydatabasename = $item.PropertyDatabase

##$CrawlComponentsLocation - location to create crawl components
$CrawlComponentsLocation = $item.CrawlComponentsLocation

##$QueryComponentsLocation - location to create query components
$QueryComponentsLocation = $item.QueryComponentsLocation

#Region of Site Query and Site Settings Service Instance
try
{
                #Start Query Processor Instance
                $wfe1SearchAndQuerySvcInstance = Get-SPEnterpriseSearchQueryAndSiteSettingsServiceInstance | where {($_.server) -match $wfe1servernamefromxml}
                Start-SPEnterpriseSearchQueryAndSiteSettingsServiceInstance -identity $wfe1servernamefromxml
                write-host $wfe1servernamefromxml "Search Query and Site Settings Service Instance has been started."

                $wfe2SearchAndQuerySvcInstance = Get-SPEnterpriseSearchQueryAndSiteSettingsServiceInstance | where {($_.server) -match $wfe2servernamefromxml}
                Start-SPEnterpriseSearchQueryAndSiteSettingsServiceInstance -identity $wfe2servernamefromxml
                write-host $wfe2servernamefromxml "Search Query and Site Settings Service Instance has been started."

                $wfe3SearchAndQuerySvcInstance = Get-SPEnterpriseSearchQueryAndSiteSettingsServiceInstance | where {($_.server) -match $wfe3servernamefromxml}
                Start-SPEnterpriseSearchQueryAndSiteSettingsServiceInstance -identity $wfe3servernamefromxml
                write-host $wfe3servernamefromxml "Search Query and Site Settings Service Instance has been started."
}
catch
{
                Write-Output $_
}

#End Region

#Create Search Service Application
If ($SearchAppPoolName  -ne $NULL -and $searchserviceappname -ne $NULL)
{
                ##Remove-SPServiceApplicationPool $SearchAppPoolName
                Write-Host "Creating Search Service Application pool ..."
                $pool = New-SPServiceApplicationPool -Name $SearchAppPoolName -Account $ManagedAcctUserName
                write-host $pool "successfully created". -foreground green
               
                $searchserviceapp = new-spenterprisesearchserviceapplication -name $searchserviceappname -applicationpool $SearchAppPoolName

                write-host $searchserviceapp "successfully created". -foreground green

}
#EndRegion

#Create service application proxy

if($SearchAppProxyName -ne $null -and $SearchServiceAppName -ne $null)
{
$ssaproxy = New-SPEnterpriseSearchServiceApplicationProxy -Name $SearchAppProxyName -SearchApplication $SearchServiceAppName
write-host $ssaproxy  "has been generated successfully." -ForegroundColor green

}
else
{
Write-Host "Error: Search Application Name '($($SearchAppProxyName))' does not exist" -ForegroundColor Red
}
#EndRegion

#Start App server 2 Search Service Instance
$appserver2searchInstance = Get-SPEnterpriseSearchServiceInstance | where {($_.server) -match $App2servernamefromxml}
if ($appserver2searchInstance.status -eq "Disabled")
{
Start-SpEnterpriseSearchServiceInstance -identity $appserver2searchInstance
}

## Wait
Write-Host -ForegroundColor Blue " - Waiting for App server 2 Search Service Instance to start..." -NoNewline
While ($appserver2searchInstance.status -ne "Online")
{
Write-Host -ForegroundColor Blue "." -NoNewline
#start-sleep 1
$appserver2searchInstance = Get-SPEnterpriseSearchServiceInstance | where {($_.server) -match $App2servernamefromxml}
}
Write-Host -BackgroundColor yellow -ForegroundColor Black " ......: App server 2 Search Service Started!"
#EndRegion

#Start App server 3 Search Service Instance
$appserver3searchInstance = Get-SPEnterpriseSearchServiceInstance | where {($_.server) -match $App3servernamefromxml}
if ($appserver3searchInstance.status -eq "Disabled")
{
Start-SpEnterpriseSearchServiceInstance -identity $App3servernamefromxml
}
## Wait
Write-Host -ForegroundColor Blue " - Waiting for App server 3 Search Service Instance to start..." -NoNewline
While ($appserver3searchInstance.status -ne "Online")
{
Write-Host -ForegroundColor Blue "." -NoNewline
##start-sleep 1
$appserver3searchInstance = Get-SPEnterpriseSearchServiceInstance | where {($_.server) -match $App3servernamefromxml}
}
Write-Host -BackgroundColor yellow -ForegroundColor Black " ......: App server 3 Search Service Started!"

#Start Web Server 1 Search Service Instance
$wfe1searchInstance = Get-SPEnterpriseSearchServiceInstance | where {($_.server) -match $wfe1servernamefromxml}
if ($wfe1searchInstance.status -eq "Disabled")
{
Start-SpEnterpriseSearchServiceInstance -identity $wfe1servernamefromxml
}
## Wait
Write-Host -ForegroundColor Blue " - Waiting for Web Server 1 Search Service Instance to start..." -NoNewline
While ($wfe1searchInstance.status -ne "Online")
{
Write-Host -ForegroundColor Blue "." -NoNewline
##start-sleep 1
$wfe1searchInstance = Get-SPEnterpriseSearchServiceInstance | where {($_.server) -match $wfe1servernamefromxml}
}
Write-Host -BackgroundColor yellow -ForegroundColor Black " ......: Web Server 1 Search Service Started!"
#EndRegion

#Start Web Server 2 Search Service Instance
$wfe2searchInstance = Get-SPEnterpriseSearchServiceInstance | where {($_.server) -match $wfe2servernamefromxml}
if ($wfe2searchInstance.status -eq "Disabled")
{
Start-SpEnterpriseSearchServiceInstance -identity $wfe2servernamefromxml
}
## Wait
Write-Host -ForegroundColor Blue " - Waiting for Web Server 2 Search Service Instance to start..." -NoNewline
While ($wfe2searchInstance.status -ne "Online")
{
Write-Host -ForegroundColor Blue "." -NoNewline
##start-sleep 1
$wfe2searchInstance = Get-SPEnterpriseSearchServiceInstance | where {($_.server) -match $wfe2servernamefromxml}
}
Write-Host -BackgroundColor yellow -ForegroundColor Black " ......: Web Server 2 Search Service Started!"
#EndRegion

#Start Web Server 3 Search Service Instance
$wfe3searchInstance = Get-SPEnterpriseSearchServiceInstance | where {($_.server) -match $wfe3servernamefromxml}
if ($wfe3searchInstance.status -eq "Disabled")
{
Start-SpEnterpriseSearchServiceInstance -identity $wfe3servernamefromxml
}

## Wait
Write-Host -ForegroundColor Blue " - Waiting for Web Server 3 Search Service Instance to start..." -NoNewline
While ($wfe3searchInstance.status -ne "Online")
{
Write-Host -ForegroundColor Blue "." -NoNewline
##start-sleep 1
$wfe3searchInstance = Get-SPEnterpriseSearchServiceInstance | where {($_.server) -match $wfe3servernamefromxml}
}
Write-Host -BackgroundColor yellow -ForegroundColor Black " ......: Web Server 3 Search Service Started!"
#EndRegion


##Provision Search Administration Component
$appserver2searchInstance = get-spenterprisesearchserviceinstance  | where {($_.server) -match $App2servernamefromxml}
set-spenterprisesearchadministrationcomponent –searchapplication $SearchServiceAppName –searchserviceinstance $appserver2searchInstance
write-host " Provisioning Search AdministrationComponent is completed." -foreground green
#EndRegion

##Create Crawl Topology
try
{


                write-host Getting Initial Crawl Topology
                # Retrieve the active topology
                $InitialCrawlTopology = $SearchServiceAppName | Get-SPEnterpriseSearchCrawlTopology -Active


                write-host Cloning Crawl Topology
                # Clone the topology
                $CrawlTopology = $SearchServiceAppName | New-SPEnterpriseSearchCrawlTopology -Clone -CrawlTopology $InitialCrawlTopology

                #$crawlDB - variable to hold newly created database
                $crawlDB = New-SPEnterpriseSearchCrawlDatabase -SearchApplication $SearchServiceAppName  -DatabaseName $crawlDatabaseName -Dedicated

                write-host Creating new crawl component
                # Create the new crawl component
                $CrawlDatabase0 = ([array]($SearchServiceAppName | Get-SPEnterpriseSearchCrawlDatabase))[0]
                $CrawlDatabase1 = ([array]($SearchServiceAppName | Get-SPEnterpriseSearchCrawlDatabase))[1]
                $CrawlComponent0 = New-SPEnterpriseSearchCrawlComponent -CrawlTopology $CrawlTopology -CrawlDatabase $CrawlDatabase0 -SearchServiceInstance $appserver2searchInstance -IndexLocation $CrawlComponentsLocation
                $CrawlComponent1 = New-SPEnterpriseSearchCrawlComponent -CrawlTopology $CrawlTopology -CrawlDatabase $CrawlDatabase0 -SearchServiceInstance $appserver2searchInstance -IndexLocation $CrawlComponentsLocation
                $CrawlComponent2 = New-SPEnterpriseSearchCrawlComponent -CrawlTopology $CrawlTopology -CrawlDatabase $CrawlDatabase1 -SearchServiceInstance $appserver3searchInstance -IndexLocation $CrawlComponentsLocation
                $CrawlComponent3 = New-SPEnterpriseSearchCrawlComponent -CrawlTopology $CrawlTopology -CrawlDatabase $CrawlDatabase1 -SearchServiceInstance $appserver3searchInstance -IndexLocation $CrawlComponentsLocation

                write-host Activating new crawl topology
                # Activate the new crawl topology
                $CrawlTopology | Set-SPEnterpriseSearchCrawlTopology -Active
                Write-Host -ForegroundColor white Waiting for the old crawl topology to become inactive
                do {write-host -NoNewline .;Start-Sleep 1;} while ($InitialCrawlTopology.State -ne "Inactive")
}
catch
                {
                                Write-Output $_
                }

##Create Query Topology
try
{

write-host Retrieving Active Topology
                                # Retrieve the Active Query Topology
                                $InitialQueryTopology = $SearchServiceAppName | Get-SPEnterpriseSearchQueryTopology -Active


                                write-host Cloning Query Topology
                                # Create New topology
                                $QueryTopology = $SearchServiceAppName | New-SPEnterpriseSearchQueryTopology -Partitions 2     


                                write-host Adding Query Components


                                $IndexPartition0 = ([array](Get-SPEnterpriseSearchIndexPartition -QueryTopology $QueryTopology))[0]                               
                                $IndexPartition1 = ([array](Get-SPEnterpriseSearchIndexPartition -QueryTopology $QueryTopology))[1]

                                $QueryComponent0 = New-SPEnterpriseSearchQuerycomponent -QueryTopology $QueryTopology -IndexPartition $IndexPartition0 -SearchServiceInstance $wfe1searchInstance -IndexLocation $QueryComponentsLocation
                                $QueryComponent1 = New-SPEnterpriseSearchQuerycomponent -QueryTopology $QueryTopology -IndexPartition $IndexPartition1 -SearchServiceInstance $wfe1searchInstance -IndexLocation $QueryComponentsLocation                               
                                $QueryComponent2 = New-SPEnterpriseSearchQuerycomponent -QueryTopology $QueryTopology -IndexPartition $IndexPartition0 -SearchServiceInstance $wfe2searchInstance -IndexLocation $QueryComponentsLocation                               
                                $QueryComponent3 = New-SPEnterpriseSearchQuerycomponent -QueryTopology $QueryTopology -IndexPartition $IndexPartition1 -SearchServiceInstance $wfe2searchInstance -IndexLocation $QueryComponentsLocation                               

                                # Reuse the existing property database
                                #$PropertyDatabase0 = ([array]($SearchServiceAppName | Get-SPEnterpriseSearchPropertyDatabase))[0]

                                #Create New Property Database
                                $searchApp = Get-SPEnterpriseSearchServiceApplication $SearchServiceAppName
                                $PropertyDatabase = New-SPEnterpriseSearchPropertyDatabase -SearchApplication $searchApp -DatabaseName $propertydatabasename


                                # Assign two index partitions to the property database
                                $IndexPartition0 | Set-SPEnterpriseSearchIndexPartition -PropertyDatabase $PropertyDatabase
                                $IndexPartition1 | Set-SPEnterpriseSearchIndexPartition -PropertyDatabase $PropertyDatabase
                               
                                write-host Activating new query topology
                                # Activate the new query topology
                                $QueryTopology | Set-SPEnterpriseSearchQueryTopology -Active
                                Write-Host -ForegroundColor white Waiting for the old query topology to become inactive
                                do{write-host -NoNewline.;Start-Sleep 1;} while ($InitialQueryTopology.State -ne "Inactive")


}
catch
                {
                                Write-Output $_
                }
#EndRegion
##region to set default access account.
try
{
                Write-Host "Setting the default content access account..."
                $SearchServiceAppName | Set-SPEnterpriseSearchServiceApplication -DefaultContentAccessAccountName $ContentAccessAcctName -DefaultContentAccessAccountPassword $ContentAccessAcctPassword -Debug:$false    
                write-host "Default content access account has been set to access crawlers." -foreground green
}
catch
                {
                                Write-Output $_
                }
#EndRegion

#Region Crawl Target Configuration
Function CrawlTargetConfiguration()
{
Write-Host -ForegroundColor Blue "- Configuring Crawl Target Server..." -NoNewline
                try
                {

                $svc=[Microsoft.SharePoint.Administration.SPWebServiceInstance]::LocalContent
                $svc.DisableLocalHttpThrottling
                $svc.DisableLocalHttpThrottling=$true
                $svc.Update()
                $listOfUri = new-object System.Collections.Generic.List[System.Uri](1)
                $zoneUrl = [Microsoft.SharePoint.Administration.SPUrlZone]'Default'

                ## This is your web application url(e.g. http://xxx.com, note crawl target configuration is
                ## per web application
                $webAppUrl = $item.WebApplicationUrl
                $webApp = Get-SPWebApplication -Identity $webAppUrl
                $webApp.SiteDataServers.Remove($zoneUrl) 

                ## This is your crawl target server
                ## You can use a server name e.g.  http://crawltargetservername, or a URL e.g. ##http://webappurl
                ## you can also add multiple crawl target servers
                ## this assumes that the web application is provisioned on port 80, otherwise specify the port no
                $URLOfDedicatedMachine = New-Object System.Uri($item.CrawlTargetMachineUrl)

                $listOfUri.Add($URLOfDedicatedMachine);
                $webApp.SiteDataServers.Add($zoneUrl,$listOfUri);
                $WebApp.Update()

                ##Verify the crawl target configuration, the following script will list the configured crawl target urls
                $webAppUrl = $item.WebApplicationUrl
                $webApp = Get-SPWebApplication -Identity $webAppUrl
                $webapp.SiteDataServers | fl | Out-String


                write-host $item.crawltargetserver has been configured as crawl target server successfully -ForegroundColor Green


                }
                catch
                {
        Write-Output $_
                }             
               
}CrawlTargetConfiguration
#EndRegion

$EndDate = Get-Date
Write-Host -ForegroundColor White "-----------------------------------"
Write-Host -ForegroundColor White "| Search Creation completed |"
Write-Host -ForegroundColor White "| Started on: $StartDate |"
Write-Host -ForegroundColor White "| Completed:  $EndDate |"
Write-Host -ForegroundColor White "-----------------------------------"
Stop-Transcript
Invoke-Item $LogFile           

Below is the topology that has been created

//SetInputs.xml
<?xml version="1.0" encoding="utf-8" ?>
<SearchTopologyInputs>
  <SearchAppPoolName>SearchServiceApplicationPool</SearchAppPoolName>
  <DefaultContentAccessAcctName>domain\username</DefaultContentAccessAcctName>
  <DefaultContentAccessAcctPassword>password</DefaultContentAccessAcctPassword>
  <ManagedAccountName>domain\username</ManagedAccountName>
  <ManagedAccountPassword>password</ManagedAccountPassword>
  <SearchServiceApplicationName> Search Service Application</SearchServiceApplicationName>
  <SearchServiceApplicationProxyName> Search Service Application Proxy</SearchServiceApplicationProxyName>
  <App2servername> App2servername </App2servername> 
  <App3servername> App3servername </App3servername> 
  <wfe1servername> wfe1servername </wfe1servername> 
  <wfe2servername> wfe2servername </wfe2servername>
  <wfe3servername> wfe3servername </wfe3servername>
  <CrawlDatabase>Search_Service_Application_CrawlStore02</CrawlDatabase>
  <PropertyDatabase> Search_Service_Application_PropertyStore02</PropertyDatabase>
  <CrawlComponentsLocation>E:\crawlcomponents</CrawlComponentsLocation>
  <QueryComponentsLocation>E:\querycomponents</QueryComponentsLocation>
  <DBServer1>INSQL06_01</DBServer1>
  <DBServer2>INSQL06_02</DBServer2>
  <DBServer3>INSQL06_03</DBServer3>
  <crawltargetserver>crawltargetservername</crawltargetserver>
  <WebApplicationUrl>http://webappurl</WebApplicationUrl>
  <CrawlTargetMachineUrl>http://crawltargetservername</CrawlTargetMachineUrl>
</SearchTopologyInputs>