Skip to content

Instantly share code, notes, and snippets.

@asadrefai
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save asadrefai/f5ef3120fae07ec93511 to your computer and use it in GitHub Desktop.

Select an option

Save asadrefai/f5ef3120fae07ec93511 to your computer and use it in GitHub Desktop.
SharePoint custom list view to show items inside a folder
function Create-ListViewInner()
{
param(
[Parameter(Mandatory=$true)][string]$url,
[Parameter(Mandatory=$false)][System.Net.NetworkCredential]$credentials,
[Parameter(Mandatory=$true)][string]$listName,
[Parameter(Mandatory=$true)][string]$viewName
)
begin{
try
{
#get Client Object
$context = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$context.Credentials = $credentials
#Retrieve List
$list = $context.Web.Lists.GetByTitle($listName)
$context.Load($list)
$context.ExecuteQuery()
$contentTypes = $context.Web.Lists.GetByTitle($listName).ContentTypes
$context.Load($contentTypes)
$context.ExecuteQuery()
$ct = $contentTypes | Where {$_.Name -eq "Folder"}
}
catch
{
Write-Host "Error while getting context. Error -->> " + $_.Exception.Message -ForegroundColor Red
}
}
process{
try
{
$viewQuery = '<OrderBy><FieldRef Name="Created" Ascending="FALSE" /></OrderBy>'
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("Title")
$viewFields.Add("Field1")
$viewFields.Add("Field2")
$viewFields.Add("Field3")
$ViewInfo = New-Object Microsoft.SharePoint.Client.ViewCreationInformation
$ViewInfo.Query = $viewQuery
$ViewInfo.RowLimit = 30
$ViewInfo.ViewFields = $viewFields
$ViewInfo.Title = $viewName
$ViewInfo.SetAsDefaultView = $false
$view = $list.Views.Add($ViewInfo)
$context.Load($view)
$context.ExecuteQuery()
$view.DefaultViewForContentType = $true
$view.ContentTypeId = $ct.Id
$view.Update()
$context.Load($view)
$context.ExecuteQuery()
Write-Host "View " $viewName " in list " $listName " added successfully" -ForegroundColor Green
}
catch
{
Write-Host ("Error while creating view for a List. Error -->> " + $_.Exception.Message) -ForegroundColor Red
}
}
end{
$context.Dispose()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment