Dailycode.info

Short solution for short problems

SharePoint: Create a scheduled task to run a SharePoint PowerShell script

I need to do some daily check on the SharePoint environment. If some site properties do not exist, I have to add them for that site.

The script is very easy, it just loops over the sites with "mark" in the url and then check if a certain property is present or not. If not, it adds the property to the site. I also log the start of the script execution and if a property is added, I also make a log. So I can check what sites where altered. Here's the script:

$sites=get-spsite -limit ALL
$startText = "Start CheckAllPropertiesAndFixResult"
$a = Get-Date -Format g
$a + " " +  $startText | Out-File C:\Scripts\CheckAllPropertiesAndFixResult.txt -append -width 200
foreach($site in $sites)
{
	Write-Host $site.Url
	if($site.Url -like "*/mark/*")
	{
		$web=$site.OpenWeb()
		if ($web.AllProperties["isactive"] -eq $null)
		{
			$web.AllowUnsafeUpdates=$true
			$web.AllProperties["isactive"]=1
			$web.Update()
			$web.AllProperties
			$web.AllowUnsafeUpdates=$false
			Write-Host "Update" $web.Url 
			$web.url  | Out-File C:\Scripts\CheckAllPropertiesAndFixResult.txt -append -width 200
		}
	}
}

As you see I had to put the full path of the out file in the script, else it didn't work.

Now in order to use this as SharePoint PowerShell in a normal PowerShell.exe I need to add the SharePoint snapin.

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue

Now the complete ps1 file look like this:

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
$sites=get-spsite -limit ALL
$startText = "Start CheckAllPropertiesAndFixResult"
$a = Get-Date -Format g
$a + " " +  $startText | Out-File C:\Scripts\CheckAllPropertiesAndFixResult.txt -append -width 200
foreach($site in $sites)
{
	Write-Host $site.Url
	if($site.Url -like "*/mark/*")
	{
		$web=$site.OpenWeb()
		if ($web.AllProperties["isactive"] -eq $null)
		{
			$web.AllowUnsafeUpdates=$true
			$web.AllProperties["isactive"]=1
			$web.Update()
			$web.AllProperties
			$web.AllowUnsafeUpdates=$false
			Write-Host "Update" $web.Url 
			$web.url  | Out-File C:\Scripts\CheckAllPropertiesAndFixResult.txt -append -width 200
		}
	}
}

Now we create a scheduled task on our SharePoint server. Choose as action: start a program. Then enter PowerShell in the Program/script textbox. Last add the file path as argument to the Add arguments (optional): textbox: &'C:\Scripts\CheckAllPropertiesAndFix.ps1'


Try to run the task and see if the result file is changed. Be sure that you set the task to run if user is not logged on.