Category Archives: Powershell

SharePoint PowerShell Backup Script with Windows Scheduler

An easy script to backup your SharePoint farm with Windows scheduler. First create a powershell script:

1-Backup a site:
Add-PSSnapin Microsoft.SharePoint.PowerShell
backup-spsite -identity $args[0] -path $args[1] -force

2-Backup the complete farm:

Add-PSSnapin Microsoft.SharePoint.PowerShell
Backup-SPFarm -Directory $args[1] -BackupMethod full

Next, create a .bat script to start the powershell script:

@echo off
SET SOURCE_SITE=http://sharepointfarm/
SET DEST=E:\SQLBackupFolder\
echo “Backup SharePoint Started at” %DATE% >> E:\SQLBackupFolder\Logs\Log.txt
powershell -command E:\SQLBackupFolder\SPbackupScripts\backupSP.ps1 %SOURCE_SITE% %DEST%
echo “Backup completed successfully at %DEST%” on %DATE% >> E:\SQLBackupFolder\Logs\Log.txt
@echo on

Now you can use the .bat start script in Windows Scheduler to backup your sharepoint farm. In the Task Scheduler, the account needs to be set with admin permissions to run it properly.

To clean up older sharepoint backups, schedule the following powershell script. This script checks the spbrtoc.xml for the number of sharepoint backups.

# Location of spbrtoc.xml
$spbrtocXML = “\\UNC backup folder\spbrtoc.xml”
# 10 Days of backup will be remaining after backup cleanup.
$days = 10
# Import the Sharepoint backup spbrtoc.xml file
[xml]$sharepointlist = gc $spbrtocXML
# Find the number of backups in spbrtoc.xml
$oldbackups = $sharepointlist.SPBackupRestoreHistory.SPHistoryObject |
? { $_.SPStartTime -lt ((get-date).adddays(-$days)) }
# Delete the backups from the Sharepoint backup spbrtoc.xml file
$oldbackups | % { $sharepointlist.SPBackupRestoreHistory.RemoveChild($_) }
# Delete the folders of the old backups on file level
$oldbackups | % { Remove-Item $_.SPBackupDirectory -Recurse }
# Save the changed spbrtoc.xml
$sharepointlist.Save($spbrtocXML)

Peoplepicker not showing diabled users

If you don’t want that disabled accounts will be show in the people picker of MOSS 2007, than run the following stsadm command to add a filter to the peoplepicker query:

stsadm -o setproperty -propertyname peoplepicker-searchadcustomfilter -propertyvalue (!userAccountControl=514) -url http://site_collection_url

To check if the query has changed, run the following stsadm command:

stsadm -o getproperty -propertyname peoplepicker-searchadcustomfilter -url http://site_collection_url

peoplepicker_query

Add User to Farm admin group PS script

I wrote a little script in PowerShell to add users to the Farm Administrator group of a SharePoint environment. You can easily customize this script for other SharePoint groups or import users from a CSV file to import multiple users into a SharePoint Group.

# <# # .DESCRIPTION #		Add users to the Farm Administrators group # # .INPUT #		- Central Admin port number #		- user or group #		- http Central admin URL # # .NOTES #		File Name	: Add_user_farm_admin_group.ps1 #		Author		: Ronald Bruinsma @ iDocs.info #		Requires	: PowerShell Version 2.0 #		Date		: 02/02/2011 # .LINK #		This script posted to: #			http://www.iDocs.info # # #>
# ##
# # Start of script
# ##

#Include the SharePoint cmdlets:
#Add-PsSnapin Microsoft.SharePoint.PowerShell

Write-Host 'Add user(s) to Farm Administrator group:'
Write-Host '----------------------------------------'

# input:
$caPortNumber =  Read-Host -Prompt 'Port number of Central Admin site'
$URL = Read-Host -Prompt 'URL of the Central Admin site'
	do{
	$userToAdd =  Read-Host -Prompt 'User to add to Farm Admin group '

	#create a website object:
	$site = new-Object Microsoft.SharePoint.SPSite("http://"+$URL+":"+$caPortNumber)
	$web = $site.RootWeb

	#get the Farm administrators group:
	$farmadministrators = $web.SiteGroups["Farm Administrators"]

	#add the user to the Farm administartor group:
	$farmadministrators.AddUser($userToAdd,"","New Sharepoint Farm Admins","")

	#round up
	Write-Host '----------------------------------------'
	Write-Host "Succesfully added " $userToAdd " to the Farm administrator group on the CA site: " $URL":"$caPortNumber
	Write-Host '----------------------------------------'
	Write-Host 'Current users in Farm Administrator group:'
	foreach ($user in $farmadministrators.users)
	{
	Write-Host $user
	}
	Write-Host '----------------------------------------'

	# Add another user to the Farm Administrator group? if yes, start all over again.
    $addAnotherUser = Read-Host 'Add another user to the Farm Administrator group? (Y/N)'
}
# if no, than quit the script
until ($addAnotherUser -eq 'N')

#dipose everything:
$web.Dispose()
$site.Dispose()

WSS Usage Application SP2010 PowerShell script

Use this script to create a WSS Usage Application in a SharePoint 2010 farm with a nice DataBase name.

# <# # .DESCRIPTION #		This script is for creating WSS Usage Application in SharePoint 2010 #		with a 'clean' database name. # # .USAGE #		Run this PS script on the admin server, start the PS as administrator #		with enough database permissions. # # .NOTES #		File Name	: Create_wss_usage_app.ps1 #		Author		: Ronald Bruinsma @ iDocs #		Requires	: PowerShell Version 2.0 #		Date		: 24 September 2010 # # .LINK #		URL		: http://www.idocs.info # #>
# ##
# # Start of script
# ##

#Include the SharePoint cmdlets:
#Add-PsSnapin Microsoft.SharePoint.PowerShell # remove first '#' if needed

try
{
	$CheckSPUsageApplicationExists = Get-SPUsageApplication
	If ($CheckSPUsageApplicationExists -eq $Null)
	{
	# First some variables:
	$WSSUsageApplicationName	= read-host -prompt 'Name for the WSS Usage Application'
	$DBServerName				= read-host -prompt 'Database server name (use FQDN)'
	$WSSUsageDataBaseName		= read-host -prompt 'Database name for this appliction'

		Write-Host "Creating WSS Usage Application..."
		New-SPUsageApplication -Name $WSSUsageApplicationName -DatabaseServer $DBServerName -DatabaseName $WSSUsageDataBaseName | Out-Null
		Write-Host "Created WSS Usage Application."
	}
	Else {Write-Host "WSS Usage Application allready exists..."}
}
catch
{
		Write-Output $_
}

Creating SharePoint 2010 Site Collections with a Powershell Script

I’ve created the following PowersShell 2.0 script for creating Site Collections in a SharePoint 2010 environment. You can define the following variables:

  • Create a new Managed path (Explicit or not)
  • Create a new Content Database or use a existing one
  • Associated groups will be created
  • First & Second Administrator
  • Template
  • Name, Description Site Collection

My next step with this script is the possibility to read all the variables from a Excel sheet. That will give you the possibility to create numerous Site Collections from one Excel sheet.

# <# # .DESCRIPTION #		This script is for creating a Site Collection within a Web application, #		with owner, member and reader group and users. # .NOTES #		File Name	: Create_SiteCollection_Groups.ps1 #		Author		: Ronald Bruinsma @ iDocs #		Requires	: PowerShell Version 2.0 #		Date		: 30 August 2010 # # .LINK #		URL		: http://www.idocs.info # #>
# ##
# # Start of script
# ##

# ---- CONFIGURATION BLOCK ----

#Include the SharePoint cmdlets:
#Add-PsSnapin Microsoft.SharePoint.PowerShell

#user input and set farm variables
	Write-Host 'Create SharePoint 2010 Site Collection with permissions and groups'
	Write-Host '----------------------------------------------------------'
	Write-Host 'Site Collection information:'
	Write-Host '----------------------------------------------------------'

	#Managed path needed or not?
	$strContinue_managedPath = read-host -prompt 'Create a new Managed Path? (Y/N)'
	if ($strContinue_managedPath -eq 'Y'){
		$sp_siteCollectionManagedPath = Read-Host 'Managed Path name <managed_path_name>?'
		$sp_webapp_name_URL = Read-Host -Prompt 'Web application name <http://webapp_name>?'

		$strContinue_managedPath_Explicit = read-host -prompt 'Explicit inclusion? (Y/N)'
			if ($strContinue_managedPath_Explicit -eq 'Y'){
		 		Write-Host '----------------------------------------------------------'
				Write-Host 'Created this managed path:'
				New-SPManagedPath -RelativeURL $sp_siteCollectionManagedPath -WebApplication $sp_webapp_name_URL -Explicit
				$strContinue_managedPath_Explicit = 'Y'
				}
			else
			{
				Write-Host '----------------------------------------------------------'
				Write-Host 'Created this managed path:'
				New-SPManagedPath -RelativeURL $sp_siteCollectionManagedPath -WebApplication $sp_webapp_name_URL
			}
		Write-Host '----------------------------------------------------------'
		Write-Host 'Web application + managed path used for Site Collection:'
		$sp_webapp_name = $sp_webapp_name_URL + '/' + $sp_siteCollectionManagedPath + '/'
		Write-Host $sp_webapp_name
		Write-Host '----------------------------------------------------------'
	}
	else
	{
		#No Managed path needed, continue the script:
		Write-Host '----------------------------------------------------------'
		$sp_webapp_name_URL = Read-Host -Prompt 'Web application name <http://webapp_name>?'
		Write-Host '----------------------------------------------------------'
		Write-Host 'Available Managed Paths:'
		$sp_available_mangedPaths = Get-SPManagedPath -WebApplication $sp_webapp_name_URL
		foreach ($path in $sp_available_mangedPaths)
		{
			$path
		}
		Write-Host '----------------------------------------------------------'
		$sp_siteCollectionManagedPath = Read-Host -Prompt 'Managed Path to use?'
		$sp_webapp_name = $sp_webapp_name_URL + '/' + $sp_siteCollectionManagedPath + '/'
	}

	#New Content Database needed or not?
	$strContinue_contentDatabase = read-host -prompt 'Create a new Content Database? (Y/N)'
	if ($strContinue_contentDatabase -eq 'Y'){
		$sp_contentdatabase_name = Read-Host -Prompt 'Name for new Content Database?'
		Write-Host '----------------------------------------------------------'
		Write-Host 'Created this Content Database:'
		New-SPContentDatabase -Name $sp_contentdatabase_name -WebApplication $sp_webapp_name_URL
	}
	else
	{
		#No Content Database needed, continue the script:
		Write-Host '----------------------------------------------------------'
		Write-Host 'Available Content Databases:'
		Write-Host '----------------------------------------------------------'
		$sp_available_contentDatabases = Get-SPContentDatabase -WebApplication $sp_webapp_name_URL
		foreach ($db in $sp_available_contentDatabases)
		{
			$db.Name
		}
		Write-Host '----------------------------------------------------------'
		$sp_contentdatabase_name = Read-Host -Prompt 'ContentDatabase to use for this Site Collection?'
	}

	$sp_siteCollection_name = Read-Host -Prompt 'Site Collection name (if Managed Path is explicit than leave empty)?'
	$sp_siteCollection_description = Read-Host -Prompt 'Site Collection description?'
	Write-Host '----------------------------------------------------------'
	Write-Host 'Template CODES'
	Write-Host '----------------------------------------------------------'
	Write-Host ' Name                 Title                                    LocaleId   Custom'
	Write-Host ' —-------             ----—–----—–                             ---—–      ---——'
	Write-Host ' GLOBAL#0             Global template                          1033       False'
	Write-Host ' STS#0                Team Site                                1033       False'
	Write-Host ' STS#1                Blank Site                               1033       False'
	Write-Host ' STS#2                Document Workspace                       1033       False'
	Write-Host ' MPS#0                Basic Meeting Workspace                  1033       False'
	Write-Host ' MPS#1                Blank Meeting Workspace                  1033       False'
	Write-Host ' MPS#2                Decision Meeting Workspace               1033       False'
	Write-Host ' MPS#3                Social Meeting Workspace                 1033       False'
	Write-Host ' MPS#4                Multipage Meeting Workspace              1033       False'
	Write-Host ' CENTRALADMIN#0       Central Admin Site                       1033       False'
	Write-Host ' WIKI#0               Wiki Site                                1033       False'
	Write-Host ' BLOG#0               Blog                                     1033       False'
	Write-Host ' SGS#0                Group Work Site                          1033       False'
	Write-Host ' TENANTADMIN#0        Tenant Admin Site                        1033       False'
	$sp_siteCollection_template_code = Read-Host -Prompt 'Site Collection template code?'
	Write-Host '----------------------------------------------------------'
	Write-Host 'Site Collection Primary Adminitrator information:'
	Write-Host '----------------------------------------------------------'
	$sp_website_primaryLogin_name = Read-Host -Prompt 'Primary Administrator Login name (?'
	$sp_website_primaryDisplay_name = Read-Host -Prompt 'Primary Administrator Display name?'
	$sp_website_primaryEmail_name = Read-Host -Prompt 'Primay Administrator Email address?'
	Write-Host '----------------------------------------------------------'
	Write-Host 'Site Collection Secondary Adminitrator information:'
	Write-Host '----------------------------------------------------------'
	$sp_website_secondaryLogin_name = Read-Host -Prompt 'Secondary Administrator Login name (?'
	$sp_website_secondaryDisplay_name = Read-Host -Prompt 'Secondary Administrator Display name?'
	$sp_website_secondaryEmail_name = Read-Host -Prompt 'Secondary Administrator Email address?'
 	Write-Host '----------------------------------------------------------'
	Write-Host 'Building Site Collection and associating groups and Administrators'
	Write-Host '----------------------------------------------------------'

$sp_siteCollection_URL = $sp_webapp_name + $sp_siteCollection_name
$sp_website_membersGroup_name = "$sp_siteCollection_name Members"
$ViewersGroup = "Viewers"

# ---- CREATE SITE COLLECTION BLOCK ----

#if Managed path is Explicit than use this Create Site Collection, first check:
$sp_used_mangedPaths = Get-SPManagedPath -WebApplication $sp_webapp_name_URL
		foreach ($path in $sp_used_mangedPaths)
		{
			if (($path.Name -eq $sp_siteCollectionManagedPath) -and ($path.Type -eq 'ExplicitInclusion'))
			{
			$managedPath_Explicit = 'Y'
			}
			else
			{
			$managedPath_Explicit = 'N'
			}
		}

if ($managedPath_Explicit -eq 'Y'){
	$sp_siteCollection_Explicit = $sp_webapp_name_URL + '/' + $sp_siteCollectionManagedPath
	New-SPSite -Url $sp_siteCollection_Explicit –ContentDatabase $sp_contentdatabase_name  –Description $sp_siteCollection_description  -Template $sp_siteCollection_template_code -OwnerAlias $sp_website_primaryLogin_name –OwnerEmail $sp_website_primaryEmail_name -SecondaryOwnerAlias $sp_website_secondaryLogin_name -SecondaryEmail $sp_website_secondaryEmail_name
	$sp_createdSiteCollection_URL = $sp_siteCollection_Explicit
	}
	else
	{
	#Create Site Collection:
	New-SPSite -Url $sp_siteCollection_URL –ContentDatabase $sp_contentdatabase_name -Name $sp_siteCollection_name –Description $sp_siteCollection_description  -Template $sp_siteCollection_template_code -OwnerAlias $sp_website_primaryLogin_name –OwnerEmail $sp_website_primaryEmail_name -SecondaryOwnerAlias $sp_website_secondaryLogin_name -SecondaryEmail $sp_website_secondaryEmail_name
	$sp_createdSiteCollection_URL = $sp_webapp_name + $sp_siteCollection_name
	}
$web = Get-SPWeb $sp_createdSiteCollection_URL
##Associate deafault groups and administrators to Site Collection:
$web.CreateDefaultAssociatedGroups($sp_website_primaryLogin_name,$sp_website_secondaryLogin_name,"")
$sp_SiteCollection_PrimaryAdmin = Get-SPUser $sp_website_primaryLogin_name -Web $sp_createdSiteCollection_URL
$sp_SiteCollection_PrimaryAdmin.Name = $sp_website_primaryDisplay_name
$sp_SiteCollection_PrimaryAdmin.Update()
$sp_SiteCollection_SecondaryAdmin = Get-SPUser $sp_website_secondaryLogin_name -Web $sp_createdSiteCollection_URL
$sp_SiteCollection_SecondaryAdmin.Name = $sp_website_secondaryDisplay_name
$sp_SiteCollection_SecondaryAdmin.Update()
# Finish by disposing of the SPWeb object
$web.Dispose()

Read-Host -Prompt 'Finished....?:'

Suggestions and Ideas for this Script are welcome!

PowerShell script create WebApp and Site Collection SharePoint 2010

With the following powershell script you can build webapplications and site collections in SharePoint 2010:

#Include the SharePoint cmdlets
#Add-PsSnapin Microsoft.SharePoint.PowerShell

do
{
#user input and set farm variables
Write-Host ‘Create SharePoint 2010 Web application and Site Collection’
Write-Host ‘———————————————————-’
Write-Host ‘First Enter some variables’

$sp_webapp_name = read-host -prompt ‘Web application name:’
$sp_webapp_port = read-host -prompt ‘Web application port:’
$sp_webapp_hostheader = read-host -prompt ‘Web application host header:’
$sp_webapp_url = ‘http://’ + $sp_webapp_hostheader
$sp_webapp_apppool = read-host -prompt ‘Web application pool name:’
$sp_webapp_apppoolaccount = read-host -prompt ‘Web application pool account:’
$sp_webapp_databasename = read-host -prompt ‘Web application pool database name:’
$sp_webapp_databaseserver = read-host -prompt ‘Web application database server name:’

#Create a new Web Application
new-spwebapplication -name $sp_webapp_name -Port $sp_webapp_port -HostHeader $sp_webapp_hostheader -URL $sp_webapp_url -ApplicationPool $sp_webapp_apppool -ApplicationPoolAccount $sp_webapp_apppoolaccount -DatabaseName $sp_webapp_databasename -DatabaseServer $sp_webapp_databaseserver

Write-Host ‘Web application is configured’
$strContinue = read-host -prompt ‘Continue creating a Site Collection? (Y/N)’
if ($strContinue -eq ‘Y’){

# Create SharePoint 2010 Site Collection
# base template values

Write-Host ‘Create SharePoint 2010 Site Collection:’
Write-Host ‘ Name                 Title                                    LocaleId   Custom’
Write-Host ‘ ——                 —-—–                                    ——–       –——’
Write-Host ‘ GLOBAL#0             Global template                          1033       False’
Write-Host ‘ STS#0                Team Site                                1033       False’
Write-Host ‘ STS#1                Blank Site                               1033       False’
Write-Host ‘ STS#2                Document Workspace                       1033       False’
Write-Host ‘ MPS#0                Basic Meeting Workspace                  1033       False’
Write-Host ‘ MPS#1                Blank Meeting Workspace                  1033       False’
Write-Host ‘ MPS#2                Decision Meeting Workspace               1033       False’
Write-Host ‘ MPS#3                Social Meeting Workspace                 1033       False’
Write-Host ‘ MPS#4                Multipage Meeting Workspace              1033       False’
Write-Host ‘ CENTRALADMIN#0       Central Admin Site                       1033       False’
Write-Host ‘ WIKI#0               Wiki Site                                1033       False’
Write-Host ‘ BLOG#0               Blog                                     1033       False’
Write-Host ‘ SGS#0                Group Work Site                          1033       False’
Write-Host ‘ TENANTADMIN#0        Tenant Admin Site                        1033       False’

$sp_sc_template = read-host -prompt ‘Site Collection template name:’
$strSameWebApp = Read-Host ‘Use same webbapplication you have just created? (Y/N)’
if ($strSameWebApp -eq ‘Y’) {$sp_sc_webappurl = ‘http://’ + $sp_webapp_name}
else {$sp_sc_webappurl = read-host -prompt ‘Site Collection webbapplication:’}
$sp_sc_name = read-host -prompt ‘Site Collection name:’
$sp_sc_language = read-host -prompt ‘Site Collection language LocaleId:’
$sp_sc_owner = read-host -prompt ‘Site Collection owner (DOMAINUSERNAME):’
new-SPSite -url $s p _sc_webappurl -OwnerAlias $sp_sc_owner -Language $sp_sc_language -Template $sp_sc_template -Name $sp_sc_name
}
# Create another Webapp and Site Collection? if yes, start all over again.
$strResponse = Read-Host ‘Do you want to Create another Webapp and Site Collecion? (Y/N)’
}

# if no, than quit the ps script
until ($strResponse -eq ‘N’)