1

I have created a custom list with a custom view called "my view". I have added a custom list in page web part zone. I need to change the web part view as "my view" using PowerShell script.

1 Answer 1

2

Try this:

Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$webURL = "http://SharePointSite"
$SPWeb = Get-SPWeb $webURL
$wpPage = $SPWeb.GetFile("Pages\Default.aspx")
$wpPage.Checkout()

$wpManager = $wpPage.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
for($i=0; $i -lt $wpManager.WebParts.Count; $i++) 
{ 
    if($wpManager.WebParts[$i].Title -eq "Posts") 
    { 
        $wp = wpManager.WebParts[$i]; 
        $wp.ViewGuid="{1E720D19-01A0-4B90-A14B-73CFC85092F8}"; 
        $wp.ViewId=8; // BaseViewID of View ex. 1 for AllItems.aspx
        $wpManager.SaveChanges($wp);
    }
}
6
  • thanks for the answer. Sorry, I have updated the question with the new requirement. Commented Jan 13, 2017 at 6:35
  • I get error for : Exception calling "SaveChanges" with "1" argument(s): "Object reference not set to an instance of an object." please Suggest any idea.
    – PGP
    Commented Jan 18, 2017 at 10:36
  • Please check object what you have used. for example, You are using $wpManager for $wpManager = $wpPage.GetLimitedWebPartManager() and save changes with $wp object like $wp.saveChanges() Commented Jan 18, 2017 at 10:39
  • My code is : $wpPage.Checkout() $wpManager = $wpPage.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared) for($i=0; $i -lt $wpManager.WebParts.Count; $i++) { if($wpManager.WebParts[$i].Title -eq "new view") { write-host -f green "Working fine" $wp = $wpManager.WebParts[$i]; $wp.ViewGuid="{377365f4-b059-4770-834b-40785d877d3b}"; $wp.ViewId=2; $wpManager.SaveChanges($wp) } }
    – PGP
    Commented Jan 18, 2017 at 10:46
  • can u pls look my code? @VirajGorajia
    – PGP
    Commented Jan 18, 2017 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.