Thursday, October 14, 2010

Grant Search Account Access to all Web Applications via PowerShell

Here’s a handy script I just whipped up.  When administering SharePoint Search, you typically have a ‘crawl account’ that is given access to all SharePoint sites via user policy.  This isn’t a terribly hard thing to do in Central Admin, but it can be a hard thing to remember =)  In CA, you go to each web app –> User Policy –> Add –> All Zones –> Type Username, full read –> OK.  Depending on how many web apps you have, this can be a little tedious. Also, if you’re trying to be sure you can provision your farm from script as much as possible, a little powershell can be handy here. This script does just that:

$accountName = "DOMAIN\CrawlAccount"

$webApps = Get-SPWebApplication
$webApps | %{
$webApp = $_
    $searchPolicy = $webApp.Policies | ?{$_.UserName -eq $accountName}
    if ($searchPolicy -eq $null){
        Write-Host "$($webApp.Url) does not have a $accountName policy, so it will be added."
        $searchPolicy = $webApp.Policies.Add($accountName, $accountName)
        $searchPolicy.PolicyRoleBindings.Add($webApp.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullRead))
        $webApp.Update()
    }else{
        Write-Host "$($webApp.Url) already has a policy for $accountName, so it will be skipped."
    }

}