Skip to content

Instantly share code, notes, and snippets.

@asadrefai
Created May 11, 2015 15:06
Show Gist options
  • Save asadrefai/c9ed8e791623acd5459e to your computer and use it in GitHub Desktop.
Save asadrefai/c9ed8e791623acd5459e to your computer and use it in GitHub Desktop.
PowerShell to create a List View of a SharePoint List
function Create-ListView()
{
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()
}
catch
{
Write-Host "Error while getting context. Error -->> " + $_.Exception.Message -ForegroundColor Red
}
}
process{
try
{
$viewQuery = '<GroupBy Collapse="TRUE" GroupLimit="30"><FieldRef Name="Title" /></GroupBy><OrderBy><FieldRef Name="Created" Ascending="FALSE" /></OrderBy><Where><Eq><FieldRef Name="YourField" /><Value Type="Boolean">1</Value></Eq></Where>'
$viewFields = New-Object System.Collections.Specialized.StringCollection
$viewFields.Add("Edit")
$viewFields.Add("Title")
$viewFields.Add("Created")
$ViewInfo = New-Object Microsoft.SharePoint.Client.ViewCreationInformation
$ViewInfo.Query = $viewQuery
$ViewInfo.RowLimit = 50
$ViewInfo.ViewFields = $viewFields
$ViewInfo.Title = $viewName
$ViewInfo.SetAsDefaultView = $false
$view = $list.Views.Add($ViewInfo)
$context.Load($list.Views)
$context.ExecuteQuery()
Write-Host "View added successfully" -ForegroundColor Green
}
catch
{
Write-Host ("Error while creating view for a List. Error -->> " + $_.Exception.Message) -ForegroundColor Red
}
}
end{
$context.Dispose()
}
}
@ameliapond
Copy link

What is $credentials ? You should provide an example of your script execution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment