Tuesday, 13 September 2011

Scripted - Creating a perfmon counter collection for monitoring the SharePoint crawl:


Contents:

  • Folder Structure
  • XCOPY
  • The CrawlLogs_Scripts folder
  • Create the data counter collection
  • Crawlcounters.config file:
  • Create the Start_Collector task:
  • Create the Stop_Collector task:
  • Create the set-execpolicy unrestricted task:
  • Run the deletelogs powershell script:
  • Create the set-execpolicy allsigned task:
  • Conclusion

This post describes a fully scripted perfmon counter collection deployment used to collect data about SharePoint crawls - complete with scheduled tasks to run the data collection and a PowerShell script to remove old logs

Folder Structure

First, on the Index server create 2 folders and grant everyone the Modify permission –

I:\Logfiles\CrawlLogs
I:\Logfiles\CrawlLogs_Scripts

XCopy


Next I use XCOPY to copy the CrawlLogs_Scripts from my desktop to the server:

cmd.exe /c  XCOPY "\_SOURCE\Crawllogs_scripts" "I:\LogFiles\Crawllogs_scripts" /E /V /I /Y > "c:\logs\copy_Crawllogs_scripts.log"

The CrawlLogs_Scripts folder

This contains the PowerShell scripts, batch files and config file that will be used to configure crawl logging


Create the data counter collection


Do this by running the create_data_collector.bat – the contents of this file are listed below – this creates the “Osearch-crawl-counters” counter, in .csv format, named “crawllog”, in the “I:\Logfiles\CrawlLogs” path, using the crawlcounters.config file
logman create counter Osearch-crawl-counters -f csv -max 250 -cnf -si 00:00:15 -o "I:\LogFiles\Crawllogs\crawllog" -cf "I:\LogFiles\Crawllogs_scripts\crawlcounters.config"

Crawlcounters.config file:


This is used to list the perfmon counters that will be logged – in this case:
"\Office Server Search Gatherer\*"
"\Office Server Search Archival Plugin(Portal_Content)\*"
"\Office Server Search Gatherer Projects(Portal_Content)\*"
"\Office Server Search Indexer Catalogs(Portal_Content)\*"
"\Office Server Search Schema Plugin(Portal_Content)\*"
The crawl in our environment runs every weekday from 17:00 – so we’ll now set the counters to collect data over this period

Create the Start_Collector task:


Now we create a scheduled task to run the “start_collector.bat” at 16:30 Mon-Fri using the SPFarm account credentials
cmd.exe /c  if not exist C:\WINDOWS\tasks\Start_Collector.job SCHTASKS /create /tn "Start_Collector" /tr "I:\LogFiles\Crawllogs_scripts\start_collector.bat" /sc weekly /D "MON,TUE,WED,THU,FRI" /st 16:30 /ru domain\SPfarm /rp password > "c\logs\add-schtask-startcollector.log"

Create the Stop_Collector task:


Now we create a scheduled task to run the “stop_collector.bat” at 04:30 Mon-Fri using the SPFarm account credentials
cmd.exe /c  if not exist C:\WINDOWS\tasks\Stop_Collector.job SCHTASKS /create /tn "Stop_Collector" /tr "I:\LogFiles\Crawllogs_scripts\stop_collector.bat" /sc weekly /D "MON,TUE,WED,THU,FRI" /st 04:30 /ru DOMAIN\SPfarm /rp password > "c:\logs\add-schtask-stopcollector.log"

Create the set-execpolicy unrestricted task:


Next we create a scheduled task to set the PowerShell execution policy to unrestricted at 05:29 Mon-Fri – this will enable us to then run the deletelogs.ps1 – a script that deletes counter logs over 10 days old and thus prevents the drive from filling up
cmd.exe /c  if not exist C:\WINDOWS\tasks\Set-execpolicy-un.job SCHTASKS /create /tn "Set-execpolicy-un" /tr "I:\LogFiles\Crawllogs_scripts\set_un.bat" /sc weekly /D "MON,TUE,WED,THU,FRI" /st 05:29 /ru DOMAIN\SPfarm /rp password > "c:\install\logs\add-schtask3.log"

Run the deletelogs powershell script:


This task runs 1 minute after the execution policy has been set to unrestricted
cmd.exe /c  if not exist C:\WINDOWS\tasks\deletelogs.job SCHTASKS /create /tn "deletelogs" /tr "I:\LogFiles\Crawllogs_scripts\deletelogs.bat" /sc weekly /D "MON,TUE,WED,THU,FRI" /st 05:30 /ru DOMAIN\SPfarm /rp password > "c:\install\logs\add-schtask4.log"
This task runs the deletelogs.bat:
powershell -command "& 'I:\LogFiles\Crawllogs_scripts\deletelogs.ps1' "
The deletlogs.bat runs the deletelogs.ps1

Deletelogs.ps1:

               
$TargetFolder = "I:\LogFiles\Crawllogs"
$cFiles = get-childitem $TargetFolder
foreach ($cFile in $cFiles)
       {
       If ($cFile.CreationTime -lt ((get-date).AddDays(-10))) 
              {
              write-host "Deleting File $cfile" -foregroundcolor "Red"
              $targetfile = "$TargetFolder\$cfile"
              del $targetfile
              }
       }

Create the set-execpolicy allsigned task:


This task resets the PowerShell execution policy at 05:35 - after the deletelogs.ps1 has been run
cmd.exe /c  if not exist C:\WINDOWS\tasks\Set-execpolicy-re.job SCHTASKS /create /tn "Set-execpolicy-re" /tr "I:\LogFiles\Crawllogs_scripts\set_re.bat" /sc weekly /D "MON,TUE,WED,THU,FRI" /st 05:35 /ru DOMAIN\SPfarm /rp password > "c:\install\logs\add-schtask5.log"
It runs the set_re.bat:
powershell -command set-executionpolicy allsigned

Conclusion


At the end of all this you get log files for the last 10 days that detail all major criteria of crawl activity – very useful



Hope this helps – I did all this because next I added the PDF Ifilter and I wanted to measure the impact
In the next blog I’ll go over how I scripted the PDF IFilter install on a MOSS 2007 environment
Cheers

Wednesday, 22 June 2011

BackConnectionHostNames PowerShell Script

- useful for SharePoint environments where you are accessing the site from the server itself:


You receive error 401.1 when you browse a Web site that uses Integrated Authentication and is hosted on IIS 5.1 or a later version




### Script ###

Param([string]$StringAdditionalUrls)
[System.String[]]$StringAdditionalUrlsArray = $StringAdditionalUrls.Split(",")
$ArrayAdditionalUrls = "$StringAdditionalUrlsArray".Split()

[string]$path = "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0\"
Write-Output "path=$path"
[string]$name = "BackConnectionHostNames"
Write-Output "name=$name"

[string]$currentvalue = (Get-Item "$path").GetValue("$name")
[System.String[]]$ArrayExistingValues = "$currentvalue".Split()
Write-Output "Current Values are: -"
ForEach ($currentAlias in $ArrayExistingValues)
                {
                Write-Output "- $currentAlias    "
                }

Write-Output "Additional Values are: -"
ForEach ($addAlias in $ArrayAdditionalUrls)
                {
                Write-Output "- $addAlias           "
                }
               
Write-Output "`nChecking current values..."
ForEach ($currentAlias in $ArrayExistingValues)
                                {
                                Write-Output "Checking $currentAlias"
                                If ($currentAlias)
                                                {             
                                                If ($newAlias)
                                                                {                                                             
                                                                If($ArrayNewUrls -notcontains $currentAlias)
                                                                                {
                                                                                Write-Output " -Adding: $currentAlias"
                                                                                $newAlias = $newAlias+" "+$currentAlias                                                            
                                                                                }
                                                                }
                                                Else
                                                                {
                                                                $newAlias = $currentAlias
                                                                Write-Output " -Adding $currentAlias"
                                                                }
                                                }                             
                                [System.String[]]$ArrayNewUrls = "$newAlias".Split()
                                }
Write-Output "`nComparing new values..."
ForEach ($addAlias in $ArrayAdditionalUrls)
                {
                Write-Output "Checking: $addAlias.."
                If ($ArrayExistingValues -contains $addAlias)
                                {
                                Write-Output " -$addAlias already exists"
                                }                             
                Else
                                {
                                Write-Output " -Adding: $AddAlias"
                                $newAlias = $newAlias+" "+$AddAlias   
                                }
                }
               
Write-Output "`nNow setting registry values..."

$newAlias = $newAlias.Trim()
[System.String[]]$ArrayNewUrls = "$newAlias".Split()



Write-Output "New list of values : -"
#ForEach ($newAlias in $ArrayNewUrls)
#             {
                Write-Output $newAlias
#             }

Set-ItemProperty -Path $path -Name $name -Value ([string[]]$ArrayNewUrls)

Write-Output "`ncompleted adding URLs to BackConnectionHostNames"

Write-Output "Completed Script: $scriptpath"


Tuesday, 21 June 2011

Check crawl status - PowerShell script

### Crawl Status script - outputs crawl status, schedule details, start address, last start and completed times

###################################################################

Param ([string]$sspURL)

$description =@'
describes crawl status
'@
### error handling ###

$scriptname = $MyInvocation.MyCommand.Name
$scriptpath = $MyInvocation.MyCommand.Path

$transcriptFile = "C:\Install\Logs\Powershell_$scriptname.log"

Start-Transcript $transcriptFile -append -force

Write-Output "Starting Script: $scriptpath"
Write-Output $description

$error.Clear()
$erroractionpreference="Stop"
$ReportErrorShowExceptionclass=$true
$ReportErrorShowInnerexception=$true
$ReportErrorShowSource=$true
$ReportErrorShowStackTrace=$true

trap {

$errorRecord = $error[0]
Write-Output "ErrorRecord:"
$errorRecord | Format-List * -Force | Out-Default
Write-Output "CategoryInfo:"
$errorRecord.CategoryInfo | Format-List * -Force | Out-Default
Write-Output "ErrorDetails:"
$errorDetails = $errorRecord.ErrorDetails
Write-Output "Message:"
$errorDetails.Message | Out-Default
Write-Output "RecommendedAction:"
$errorDetails.RecommendedAction | Out-Default
Write-Output "FullyQualifiedErrorId:"
$errorRecord.FullyQualifiedErrorId | Out-Default
Write-Output "InvocationInfo:"
$errorRecord.InvocationInfo | Format-List * -Force | Out-Default
Write-Output "TargetObject:"
$errorRecord.TargetObject | Format-List * -Force | Out-Default
Write-Output "Exception:"
$Exception = $errorRecord.Exception
for ($i = 0; $Exception; $i++, ($Exception = $Exception.InnerException))
{$Exception | Format-List * -Force | Out-Default}
;break
}


#####################################################################
### loading assemblies ###

[void][System.Reflection.Assembly]::Load("Microsoft.Office.Server.Search, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")

[void][System.Reflection.Assembly]::Load("Microsoft.Sharepoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")

[void][System.Reflection.Assembly]::Load("Microsoft.Office.Server, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")

#####################################################################

### $sspURL: e.g. "http://ssp.mydomain/ssp/admin"

$site = new-object Microsoft.SharePoint.SPSite($sspURL)

### getting spsite from $Url

$searchContext = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($site)

### getting searchContext from spsite

$content = new-object Microsoft.Office.Server.Search.Administration.Content($searchContext)

### getting admin content from searchContext

### Initializes a new instance of the Content class.


#####################################################################

$df = "local office SharePoint server sites"

$ContentSourceCollection = $content.ContentSources

$local = $ContentSourceCollection[$df]

Write-output "The crawl status is: " $local.crawlstatus
Write-output "The start time of the last crawl: " $local.CrawlStarted
Write-output "The time of the last completed crawl of a content source is: " $local.CrawlCompleted
Write-output "The content source's schedule of full crawls is: " $local.FullCrawlSchedule
Write-output "The content source's schedule of incremental crawls is: " $local.IncrementalCrawlSchedule
Write-output "The StartAddresses: " $local.StartAddresses

stop-transcript





#####################################################################

using PowerShell v2 remoting to restart SharePoint services on all the WFE servers in the farm

First - put the servers into an array:
[Void][System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")

$farm = ([Microsoft.SharePoint.Administration.SPFarm]::Local`

%{ $_.Services} `

?{$_.typename -eq "Windows SharePoint Services Web Application"}`

%{$_.instances} `

%{$_.Server} `

%{$_.Address}

)

$farm


Then use a Foreach loop to step through each server in the array and restart the services on each:

foreach ($i in $farm)


{

$session = New-PSSession -ComputerName $i

Invoke-Command -Session $session -ScriptBlock { Restart-Service Sptimerv3 }

Invoke-Command -Session $session -ScriptBlock { Restart-Service Spadmin }

}

Remember to configure the firewall correctly and to ensure WinRM is initialized and enabled for Kerberos on the remote machines

Tuesday, 14 June 2011

PowerShell script to restart the SPadmin and the SPTimerv3 service

Restart-Service -DisplayName "Windows SharePoint Services*" -Exclude "*Writer","Windows SharePoint Services Tracing","Windows SharePoint Services Search" -Verbose

Thursday, 9 June 2011

Tuesday, 7 June 2011

PowerShell script to set the SharePoint office server search Performance Level to Maximum

### This script has has C# code wrapped inside PowerShell

### The first part is the C# code that does the work mapped to a variable $Source

$Source = @"

using Microsoft.SharePoint;
using Microsoft.Office.Server.Search;
using Microsoft.Office.Server.Search.Administration;

namespace PowerShellWrapper
{
public class Program
{
public static void PerformanceLevel_set(string[] args)
{
SPSite site = new SPSite(args[0]);
SearchService ss = site.WebApplication.Farm.Services.GetValue("OSearch");
ss.PerformanceLevel = SearchPerformanceLevel.Maximum;
ss.Update();
site.Dispose();
}
}
}

"@
##################################################################

### This next bit prepares Powershell for compiling the C# code

### Obtains an ICodeCompiler from a CodeDomProvider class.

$provider = New-Object Microsoft.CSharp.CSharpCodeProvider

## Get the location for System.Management.Automation DLL

$dllName = [PsObject].Assembly.Location

## Configure the compiler parameters

$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters

### Next load the assemblies

$assemblies = @("System.dll", $dllName)

$compilerParameters.ReferencedAssemblies.AddRange($assemblies)

$compilerParameters.ReferencedAssemblies.Add("C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI\Microsoft.SharePoint.dll")

$compilerParameters.ReferencedAssemblies.Add("C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI\Microsoft.Office.Server.dll")

$compilerParameters.ReferencedAssemblies.Add("C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI\Microsoft.Office.Server.Search.dll")

$compilerParameters.IncludeDebugInformation = $true

$compilerParameters.GenerateInMemory = $true

### This next line does the work

$compilerResults = $provider.CompileAssemblyFromSource($compilerParameters, $Source)

### some error handling

if($compilerResults.Errors.Count -gt 0) {

$compilerResults.Errors
% { Write-Error ("{0}:`t{1}" -f $_.Line,$_.ErrorText) }

}

[PowerShellWrapper.Program]::PerformanceLevel_set(http://localhost/)

### Because it points to localhost it will only work when run locally

################################################################### END

SharePoint Information Architecture Diagram

Here is the template I use for Information Architecture designs. It's built using Mindjet and I flesh the nodes out with the low level d...