Tuesday, 3 November 2015

Create ListView using SharePoint PowerShell script



#Passing My Site Url
param($serverUrl)

#Begin arguments validation

if($serverUrl -eq $null)
{
$argErr = $true
}

if($argErr)
{
Write-Host
Write-Host -ForegroundColor Red "One or more parameters missing or invalid. Please see the usage and give the proper parameters"
Write-Host
Write-Host "Usage: Creating List View  messages"
Write-Host
   
    exit
}

try

{

$web = Get-SPWeb -Identity $serverUrl

Write-host
Write-host  "------Getting  List-----"
Write-host

$list = $web.Lists["Demo Ticket"]


Write-host
Write-host  "------  Making Query -----"
Write-host

$ViewName =  "Demoview" #My View Name
     
        $Query = "<Where><Eq><FieldRef Name='AssignedTo'/><Value Type='Integer'><UserID /></Value></Eq></Where>"

Write-host
Write-host  "------Getting Fields for View-----"
Write-host

$fields = $list.Views["All Items"].ViewFields.ToStringCollection()

$viewRowLimit = 50   #Row Limit
$viewPaged = $true #Paged property
$viewDefaultView = $false   #DefaultView property

Write-host
Write-host  "------Adding View  to list-----"
Write-host

$result = $list.Views.Add($ViewName, $fields, $Query, $viewRowLimit, $viewPaged, $viewDefaultView)

Write-host
Write-host  "---- Updating list -----"
Write-host

$list.Update()

Write-host
Write-host  "----- Successfully Added View to  List -Demo View  -----"
Write-host

$web.Update()
}
catch [System.SystemException]
{
  write-host "Execution stopped due to: "+$_.Message -foregroundcolor Red
}