PowerShell script to Open or Close SharePoint Web Parts

If you ever need to make changes to your SharePoint Web Parts such as hiding/showing, this post will help you to cut down unnecessary time.

Run the PowerShell script below via SharePoint Management Shell.

Change the Parameter accordingly base on your environment.

[sourcecode language=”powershell”]

$web = Get-SPWeb [URL]
$f = $web.GetFile("Pages/Default.aspx");

if( $f.CheckOutStatus -eq "None" )
{
$f.CheckOut();
}
$wpm = $f.GetLimitedWebPartManager("Shared")
$webParts = $wpm.WebParts | ? {$_.GetType().Name -eq "ContentEditorWebPart"} //Change for your own web part type
if($webParts.GetType().Name -eq "Object[]")
{
$webParts | % {
#$wpm.CloseWebPart($_);
$wpm.OpenWebPart($_);
$wpm.SaveChanges($_);
}
}
else
{
#$wpm.CloseWebPart($webParts)
$wpm.OpenWebPart($webParts)
$wpm.SaveChanges($webParts)
}

$f.CheckIn("");
$f.Publish("");

[/sourcecode]

The example above will check if the page is check out before making any changes to the web parts. Subsequently, it closes/opens all content editor web parts within it and check in and publish the page. You can additional perform more tasks such as DeleteWebPart or AddWebPart, MoveWebPart or only make changes to only certain type of web part by changing PowerShell rules

 

Leave a Reply

Your email address will not be published. Required fields are marked *