The workflow could not update the item, possibly because one or more columns for the item require a different type of information.

SharePoint Designer workflow error:
The workflow could not update the item, possibly because one or more columns for the item require a different type of information.

If you look at the workflow history nothing of value is there to clue you into what field is broken.

To track down what field is broken, I added a Pause action to my Step. Then I added a Log message before each action. Doing this helped track down the broken field.

The workflow could not update the item

Once you get the workflow working again, remember to clean up the added Log actions.

In my case, the workflow was trying to update a Person / Group field with an employee that no longer worked at the company.

System.IO.FileNotFoundException: The web application at could not be found

Online, I found a lot of different solutions to the error but none of them would solve my issue. I had written a console app that reads data from a SharePoint library, then processes the data. The process is started using a scheduled task and runs under the context of a service account. The account had contribute permissions on the library and read access to the site.

The solution:
On the SharePoint Config and Content database(s), grant the account SharePoint_Shell_Access.

After doing this, I noticed this message in the app’s call stack:

 executed on connection "Data Source=SPDevDB;Initial Catalog=SP2010_Dev_Config;Integrated Security=True;Enlist=False;Connect Timeout=15", building a SqlDataReader.
[7132]

After seeing the message, it was clear that the app was first trying to connect to the config db, then it would connect to the site/library objects.

Sort SPFileCollection by Created Date

Yes, this could be done with a CAML query, but I wanted to keep it simple.

I need to get items created in ascending order (oldest first).

My solution:


SPFileCollection items = web.GetFolder(sLawsonReports).Files;
//sort the files so we get the oldest first
List sortFiles = items.Cast().OrderBy(file => file.TimeCreated).ToList();

SharePoint Workflow Not Starting

For one reason or another, SharePoint Designer Workflows are not always starting when an item is added to a library.  This happens with document libraries and InfoPath form libraries.  I’ve seen this happen with SharePoint 2007 and SharePoint 2010.

What I’ve created is a way to identify, monitor, and start workflows.

Create two lists:

Workflow Monitor

Fields:

Site URL, List Name, Workflow Name

Workflow Monitor Logging

Fields:

Site URL, List Name, Workflow Name, List Item ID

All of the field types are the default single line of text.

Workflow Monitor will be populated with the site url, list name, and workflow name of the workflow you want to monitor.

Place the script in a folder on one of your SharePoint server. Then setup a scheduled task to run the script as needed.


<#
 loop through workflow monitor list
 get workflow item
 query associated list by created date between yesterday and today AND workflow field is empty
 if item is returned, start workflow on item.
 log item that was not started
 if there are any errors send email to DL SharePoint
#>

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

$cSite = Get-SPWeb "http://sharepointed.com"
$cList = $cSite.Lists["Workflow Monitor"]
$cListLog = $cSite.Lists["Workflow Monitor Logging"]
$errorCount = 0
$errorString = ""

foreach($config in $cList.Items)
{
	try
	{
		$fSite = Get-SPWeb $config["Site URL"].ToString()
		$wfManager = $fSite.Site.WorkFlowManager
		$fList = $fSite.Lists[$config["List Name"].ToString()]
		$fWFfield = $fList.Fields[$config["Workflow Name"].ToString()].InternalName

		#Get the list workflow
		$wfAssoc = $fList.WorkflowAssociations.GetAssociationByName($config["Workflow Name"].ToString(),"en-US")
		$wfData = $wfAssoc.AssociationData

		$sQuery = New-Object Microsoft.SharePoint.SPQuery 

		#Get all item that were created in the past day and a workflow has not ran.
		$caml = '<Where><And><IsNull><FieldRef Name="' + $fWFfield + '" /></IsNull><Geq><FieldRef Name="Created" /><Value Type="DateTime"><Today OffsetDays="-1" /></Value></Geq></And></Where>'
		$sQuery.Query = $caml
		$fItems = $fList.GetItems($sQuery)

		foreach($lItem in $fItems)
		{
			#Start workflow
			$wf = $wfManager.StartWorkFlow($lItem,$wfAssoc,$wfData,$true)

			#Create Log entry
			$newLogItem = $cListLog.Items.Add()
			$newLogItem["Site URL"] = $config["Site URL"]
			$newLogItem["List Name"] = $config["List Name"]
			$newLogItem["List Item ID"] = $lItem["ID"]
			$newLogItem["Workflow Name"] = $config["Workflow Name"]
			$newLogItem.Update()
		}
	}
	Catch
	{
		#string.format
		$errorMessage = $_.Exception.Message.ToString()
		$errorString += $config["ID"].ToString() + " " + $errorMessage + " --- "
		$errorCount++
	}
}

#If there are any errors send email
if($errorCount -gt 0)
{
	$errorString = $errorString.TrimEnd(" --- ")

	$emailSubject = "Workflow Montior Script Error"
	$emailBody = "Error running the Workflow Monitor script. <br><br> <b>Error: </b>"
	$emailBody += "$errorString <br><br>"
	$emailBody += "<a href=$cList.URL.ToString()>Workflow Monitor List </a>"
	$emailsmtpServer = "mail.doman.net"
	$emailTo = "you@sharepointed.com"
	$emailFrom = "alerts@sharepointed.com"

	Send-MailMessage -From $emailFrom -To $emailTo -Subject $emailSubject -BodyAsHtml $emailBody -SmtpServer $emailsmtpServer
}

This script will inventory your entire farm and output workflows that have failed to start int the past 59 days. *You can adjust the 59 day setting, but my farm is setup to truncate workflow history every 60 days.*


$contentWebAppServices = (Get-SPFarm).services |
? {$_.typename -eq "Microsoft SharePoint Foundation Web Application"}

$stringBuilder = New-Object System.Text.StringBuilder
$list = New-Object System.Collections.Generic.List[System.String]
$counter = 0

foreach($webApp in $contentWebAppServices.WebApplications)
{
	$webApp = Get-SPWebApplication $webApp.Url

	if($webApp -ne $null)
	{
		foreach($siteColl in $webApp.Sites)
		{
			if($siteColl -ne $null)
			{
				foreach($subWeb in $siteColl.AllWebs)
				{
					if($subWeb -ne $null)
					{
						foreach($list in $subWeb.Lists)
						{
							foreach($wf in $list.WorkflowAssociations)
							{
								if ($wf.Name -notlike "*Previous Version*")
								{
									$subWeb.Site.WorkflowManager
									$wfManager = $subWeb.Site.WorkFlowManager
									$fWFfield = $list.Fields[$wf.Name.ToString()].InternalName

									#Get the list workflow
									$wfAssoc = $list.WorkflowAssociations.GetAssociationByName($wf.Name,"en-US")
									$wfData = $wfAssoc.AssociationData

									if($wfAssoc.AutoStartCreate -eq $true)
									{
										$counter++

										$sQuery = New-Object Microsoft.SharePoint.SPQuery 

										#Get all item that were created in the past day and a workflow has not ran.
										$caml = '<Where><And><IsNull><FieldRef Name="' + $fWFfield + '" /></IsNull><Geq><FieldRef Name="Created" /><Value Type="DateTime"><Today OffsetDays="-59" /></Value></Geq></And></Where>'
										$sQuery.Query = $caml
										$fItems = $list.GetItems($sQuery) 

										$null = $stringBuilder.Append($subWeb.URL)
										$null = $stringBuilder.Append(",")
										$null = $stringBuilder.Append($list.Title)
										$null = $stringBuilder.Append(",")
										$null = $stringBuilder.Append($wf.Name.ToString())
										$null = $stringBuilder.Append("`r`n")

									}
								}
							}

						}

						$subWeb.Dispose()
					}
				}
				$siteColl.Dispose()
			}
		}
	}
}

if($counter -gt 0)
{
	out-file -filepath C:\WorkflowOutput.csv -inputobject $stringBuilder.ToString()
}

Document ID Service and Migrating Documents

You are using the Document ID Service in SharePoint and you want to move your documents to another location.  For whatever reason, you notice when you move the documents that your document id’s are lost or reset.  This can be real bad if other systems outside of SharePoint leverage the document id to locate documents in SharePoint.

Here are the steps I used to get around this.
Move the documents from location A to B, keeping the original documents in A.
Run a crawl.
Execute the script below (input your own values for the site and libraries).
Remove / delete the documents from location A. For safe measures, also empty the recycle bin, both at the site and site collection level.
Run another crawl.
Trigger the Document Id Settings to update.

What the script is doing:
Get all the documents in the Shared Documents library of site A.
Loop through the documents.
Locate the document by name in the Shared Documents library of site B.
Update the Document ID of the item.

Things you could improve on:
Get all the documents in site A and output the Name and Document ID to a csv file.
– Then process the csv file with the script.
Add logging.
– Output your pass / fail items to csv file.
Expand the search to query a site.
– Then update the returned item.

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

$sSite = Get-SPWeb "http://sharepoint.net/sites/A"
$sList = $sSite.lists["Shared Documents"]

$dSite = Get-SPWeb "http://sharepoint.net/sites/B"
$dList = $dSite.lists["Shared Documents"]

$sQuery = New-Object Microsoft.SharePoint.SPQuery
$sQuery.ViewAttributes = "Scope='Recursive'"
$sQuery.RowLimit = 2000
$sQuery.Query = '<Where><Gt><FieldRef Name="ID" /><Value Type="Counter">0</Value></Gt></Where>'

do
{
	$sItems = $sList.GetItems($sQuery)
	$sQuery.ListItemCollectionPosition = $sItems.ListItemCollectionPosition
	foreach($sI in $sItems)
	{
		$docName = $sI["Name"].ToString()
		Write-Host $docName

		$dQuery = New-Object Microsoft.SharePoint.SPQuery
		$dQuery.ViewAttributes = "Scope='Recursive'"
		$dQuery.RowLimit = 2000
		$dQuery.Query = '<Where><Eq><FieldRef Name="FileLeafRef"/><Value Type="File">' + $docName + '</Value></Eq></Where>'

		do
		{
			$dItems = $dList.GetItems($dQuery)
			$dQuery.ListItemCollectionPosition = $dItems.ListItemCollectionPosition
			foreach($dI in $dItems)
			{
				try
				{
					$dI["Document ID Value"] = $sI["Document ID Value"]
					$dI.Update()
					Write-Host $dI["Name"] " has been updated"
				}
				catch
				{
					Write-Host $dI["Name"] " ---- " $_.Exception.Message
				}
			}
		}
		while ($dQuery.ListItemCollectionPosition -ne $null)
	}
}
while ($sQuery.ListItemCollectionPosition -ne $null)

Find all Lists and Libraries Where InfoPath is Used

Recently had the need to find and update most every InfoPath form in a production farm. This, mixed with the future demise of InfoPath, prompted the need to find or write a script. The below script will traverse every list and library in a given web app. The script can be easily modified to include every web app in a farm.

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) 
{
                Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}

$fileName = "C:\xsn-" + $(Get-Date -Format "yyyyMMddHHmmss") + ".csv"

$webApp = Get-SPWebApplication "http://webApp.sharepointed.com" 
"Title `t URL `t Type" | out-file $fileName

$(foreach($siteColl in $webApp.Sites)
{
                foreach($web in $siteColl.AllWebs)
                {
                foreach($list in $web.Lists) {                        
                
                                if ($list.BaseType -eq "DocumentLibrary" -and $list.BaseTemplate -eq "XMLForm"){
                                                "$($list.title) `t $($list.parentweb.url)$($list.DefaultViewUrl) `t Library" | out-file $fileName -Append 
                                                                
                                                
                                }elseif ($list.ContentTypes[0].ResourceFolder.Properties["_ipfs_infopathenabled"]){
                                
                                                "$($list.title) `t $($list.ParentWeb.URL)$($list.DefaultViewUrl) `t List" | out-file $fileName -Append
                                                
                                                }
												else{
												$check = 0
								foreach($c in $list.ContentTypes) {
												if($c.DocumentTemplateUrl.ToString().EndsWith("xsn") -eq $true)
												{
													$check++			
												}
												}
												if($check -gt 0)
												{
													"$($list.title) `t $($list.ParentWeb.URL)$($list.DefaultViewUrl) `t List" | out-file $fileName -Append
												}
												}
												}}})

PowerShell Unable to index into an object of type Microsoft.SharePoint.SPList.

Made a change to an existing PowerShell script, then ran into this error: Unable to index into an object of type Microsoft.SharePoint.SPList

If ((Get-PSSnapIn -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{ Add-PSSnapIn -Name Microsoft.SharePoint.PowerShell }

$web = Get-SPWeb "http://sharepointed.com/sitename"
$listTask = $web.Lists["My List"]
$sItem = $listTask.GetItemById(9)

$title = $listTask["Title"]

In the script, you will notice that I’m trying to capture the title of the item. The above script wasn’t working because I failed work with this list item, instead I was trying to work with the list object.

Correct script:

If ((Get-PSSnapIn -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{ Add-PSSnapIn -Name Microsoft.SharePoint.PowerShell }

$web = Get-SPWeb "http://sharepointed.com/sitename"
$listTask = $web.Lists["My List"]
$sItem = $listTask.GetItemById(9)

$title = $sItem["Title"]

copy.asmx This item is a copy of

Using the SharePoint Web Service Copy.asmx, you may notice this message on copied items: This item is a copy of

What I was doing wrong was, I used the destination URL in place of the source URL. If you provide a source URL, you will also receive the This item is a copy of… message in the properties view of the item. To avoid the message all together I replaced the source URL with the file name.

       //bad
       cWs.CopyIntoItems(destination, destinationUrl, fields.ToArray(), myBinary, out result);
       //good
       cWs.CopyIntoItems(filename, destinationUrl, fields.ToArray(), myBinary, out result);

CopyIntoItems.asmx

Error When Updating Item Using Web Service MoveNext

Using the SharePoint REST service to update items, ran into this error:

Unable to update the sharepoint document – An error occurred while processing this request.System.Data.Services.Client.DataServiceClientException: <?

xml version=”1.0″ …

…..

at System.Data.Services.Client.DataServiceContext.SaveResult.<HandleBatchResponse>d_1e.MoveNext()

The target list was set to require checkout before items could be updated.  Once I set require checkout to No, the REST service was able to update items.

 

Person or Group Field Append or Remove a Group

Using PowerShell I needed to append a group to a Person or Group field in a list.  The same logic should apply for adding or removing a user.

Append Group:



$web = Get-SPweb "http://sharepointed.com/sites/taco/"
$list = $web.lists["Good Tacos"]

$groupName = "Taco Eaters"
$group = $web.SiteGroups[$groupName]
$GroupValue = new-Object Microsoft.SharePoint.SPFieldUserValue($web,$group.id, $group.Name)

foreach ($item in $list.items)
 {
 $groups = $item["GroupsField"]

$groups.Add($GroupValue)

$item["GroupsField"] = $groups
 $item.Update()
 }

Remove Group:



$web = Get-SPweb "http://sharepointed.com/sites/taco/"
$list = $web.lists["Good Tacos"]

$groupName = "Taco Eaters"
$group = $web.SiteGroups[$groupName]
$GroupValue = new-Object Microsoft.SharePoint.SPFieldUserValue($web,$group.id, $group.Name)

foreach ($item in $list.items)
{
$groups = $item["GroupsField"]

<span style="line-height: 1.5em;">$groupRemove = $groups | ? { $_.LookupId -eq $GroupValue.LookupId }</span>

$groups.Remove($groupRemove)

$item["GroupsField"] = $groups
$item.Update()
}