This is the second of an ongoing set of posts about doing SharePoint management with PowerShell. Part 1 is available here – and as always, use these scripts at your own risk.
In this post, I've added just a couple new functions to my "Functions.ps1" script: Get-SPFarm and Get-SPWebApplication. The goal—to be able to quickly answer simple questions about my farm such as "How many site collections do I have?". So on to the good stuff…
Get SPFarm is extremely simple—it just returns the local site. Here's the code
function global:Get-SPFarm{
return [Microsoft.SharePoint.Administration.SPFarm]::Local
}
More interesting is the Get-SPWebApplication function. We get the list of web applications on the farm from the SPFarm.Services. The function below will include the Central Administration Web Application (*Note that the CA application does not have a name, so using Get-SPWebApplication | Select Name will show 3 names—but return 4 web applications!)
function global:Get-SPWebApplication{
Get-SPFarm |% {$_.Services} | where {'$_.TYPEName -eq "Windows SharePoint Services Web Application"'} |% {$_.WebApplications} |% {Write-Output $_}
}
That's it! The full script is available for download from the Script Library. Once the functions are available, you can get great information like the number of site collections per web application using:
get-spwebapplication | %{$_.sites.count}
And the number of site collections in the farm like this:
get-spwebapplication | %{$tot=0}{$tot+=$_.sites.count}{$tot}