1/01/2016

Views.Add() Cannot find an overload for "Add" and the argument count: "8".

 

I wrote a PowerShell script to create views. It worked in PowerShell 3 on SharePoint 2013. It failed in PowerShell 2 on SharePoint 2010.

To play it safe, I copied values from an existing view to insure the correct data types…

$web = Get-SPWeb http://sharepoint/sites/training
$list = $web.lists["Announcements22"]
$v = $list.views[0]
$list.Views.add("TestView",$v.ViewFields,$v.query,30,$true,$false,$v.Type,$false)

image

As I can count to 8 (usually) and I made sure the data types were correct, I then wasted a lot of time google/binging the error message.

So I then did the obvious thing for a developer, I fired up Visual Studio. And… found that there’s a datatype weirdness on the ViewFields parameter! The Add method is expecting System.Collections.Specialized.StringCollection while the View object actually returns Microsoft.SharePoint.SPViewFieldCollection.

The type conversion works in PowerShell 3:

image

But does not work in PowerShell 2:

image

 

My workaround? 

Use a handy method built into the Microsoft.SharePoint.SPViewFieldCollection type: ToStringCollection().

image

I could also have created the StringCollection object and copied the strings over using ForEach.

image

 

So why did it work in PowerShell 3 and not PowerShell 2? No idea! I’m guessing the “smarts” behind type conversion has improved. While the two collection objects are different (SPViewFieldCollection includes a .View property), the Items collection of both contain simple Strings.

 

.

No comments:

Note to spammers!

Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.