Get SharePoint Online (Office 365 Enterprise E3) Subscription for your Business NOW

25+ PowerShell SharePoint Examples

PoweShell SharePoint examples

In this PowerShell SharePoint tutorial, we will discuss few PowerShell SharePoint examples. This PowerShell SharePoint explains, how to undo check out a page using PowerShell Script, Change Page Layout using PowerShell Script in SharePoint, how to Extract wsp from SharePoint Farm Solutions using PowerShell,

Also, we will see how to use PowerShell script to empty SharePoint Recycle Bins and how to to collect ULS logs for specific CorrelationID in SharePoint 2016/2013 using PowerShell.

We will see how to Export Site details into Excel file in SharePoint 2016/2013, PowerShell to get installed SharePoint Version Number .

If you are new to PowerShell SharePoint, then you can read an article: Working with PowerShell in SharePoint Online/2016/2013.

Any PowerShell script, you can write, debug and test script using Windows PowerShell ISE and Visual Studio Code.

SharePoint 2016 Tutorial Contents

SharePoint: Undo check out a page using PowerShell Script

This example explains how to undo check out a page using PowerShell script in SharePoint 2016/2013/2010. Recently we face one issue in one of the migration project. Some pages were coming to check out by some people and when we try to do check-in, overwrite check-out or discard check out, nothing worked for us.

Below is the PowerShell script you can use to UndoCheckOut using PowerShell for SharePoint 2013/2016. You can pass the particular page URL to do undo checkout.

Add-PSSnapin Microsoft.SharePoint.PowerShell
$spWeb = Get-SPWeb(“https://SiteURL/”)
$spFile = $spWeb.GetFile(“https://SiteURL/Pages/MyTestpage.aspx”)
$spFile.UndoCheckOut()
$spFile.CheckIn(“Checkin Done”[Microsoft.SharePoint.SPCheckinType]::MajorCheckIn)
$spFile.Update()
$spWeb.Dispose()

SharePoint 2013/2016 Change Page Layout using PowerShell Script

In this example, we will discuss how we can change a page layout using PowerSell script. We can use PowerShell to change page layout in SharePoint 2013/2016/2010.

PowerShell script to change page layout of default.aspx page in SharePoint 2013/2016

Below is the PowerShell script to change page layout of default.aspx page in a SharePoint 2013/2016 site or subsite.

Add-PSSnapin “Microsoft.SharePoint.PowerShell”
$spWeb = Get-SPWeb(“https://SiteURL”)

$spFile = $spWeb.GetFile(“https://SiteURL/Pages/default.aspx”)
$spFile.CheckOut(“Online”,$null)
$spFile.Properties[“PublishingPageLayout”] = “/SiteURL/_catalogs/masterpage/WelcomeLinks.aspx”
$spFile.Update()
$spFile.CheckIn(“Update page layout via PowerShell”,[Microsoft.SharePoint.SPCheckinType]::MajorCheckIn)
$spWeb.Dispose()

Change page layout of all the pages using PowerShell in SharePoint 2013/2016

If you want to change the page layout of all the pages then you can use the below PowerShell.

$spWeb = Get-SPWeb(“https://SiteURL”)
$pWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($spWeb)
$pSite = New-Object Microsoft.SharePoint.Publishing.PublishingSite($spWeb.Site);

$siteLayouts = $pSite.GetPageLayouts($false)
$myLayout = $siteLayouts[“/_catalogs/masterpage/WelcomeLinks.aspx”]
#$myLayout
$query = New-Object Microsoft.SharePoint.SPQuery
$query.ViewAttributes = “Scope=’RecursiveAll'”

$pages = $pWeb.GetPublishingPages($query)

foreach ($page in $pages)
{
if ($page.ContentType.Name -eq “Folder”)
{
continue
}

$page.Layout = $myLayout
$page.update()
$page.ListItem.File.Publish(“”)
$page.ListItem.File.Approve(“”)
}
$spWeb.Dispose()

This way you can change page layout in SharePoint 2013/2016 using PowerShell.

Extract wsp from SharePoint Farm Solutions using PowerShell

Below is the PowerShell script to Extract wsp from SharePoint Farm Solutions in SharePoint 2016/2013.

$farm = Get-SPFarm
$file = $farm.Solutions.Item(“solutionname.wsp”).SolutionFile
$file.SaveAs(“E:\Backup\solutionname.wsp”)

The above PowerShell script will extract wsp from farm solutions in SharePoint 2016/2013 using PowerShell.

PowerShell script to empty SharePoint Recycle Bins

Now, we will see PowerShell script to empty SharePoint Recycle Bins. Below is the PowerShell command to delete Recycle Bin using PowerShell.

$WebApp=get-spwebapplication “Enter URL”
foreach ($SPSite in $webApp.Sites)
{
#get the collection of webs
foreach($SPWeb in $SPSite.AllWebs)
{
#Empty the 1st Stage Recycle bin items PERMENANTLY
#$SPWeb.RecycleBin.DeleteAll();
#Send the 1st Stage Recycle bin items to 2nd Stage
$SPWeb.RecycleBin.MoveAllToSecondStage();

write-host “End-User Recycle Bin Items Deleted for:”
write-host $SPWeb.title “:” $SPWeb.URL “`n”
}
#Empty SharePoint site collection recycle bin (2nd Stage Recycle bin) or Admin Recycle bin
$SPSite.RecycleBin.DeleteAll();
write-host “Administrator Recycle bin Items Deleted for:” $SPSite.RootWeb.title “`n”
}

PowerShell Command to collect ULS logs for specific CorrelationID in SharePoint 2016/2013

Now, we will discuss how we can collect ULS logs for specific CorrelationID using PowerShell. Below is the PowerShell command to collect ULS logs for specific CorrelationID:

get-splogevent -starttime (get-date).addminutes(-20) | where-object { $_.correlation -eq “b66db71a-3257-4470-adf9-5c01dc59ecb3? } | fl message > c:\errors.txt

PowerShell Script to Export Site into Excel file

Below is the PowerShell script to retrieve site details using PowerShell in SharePoint 2016/2013.

Get-SPSite “http://sharepoint.company.com/sales/” | Get-SPWeb -Limit All | Select Title, Url | Export-Csv -NoTypeInformation -Path “c:\sites.csv”

PowerShell to get installed SharePoint Version Number

Now, we will see how to get installed SharePoint version number using PowerShell in SharePoint 2016/2013.

Get-Spfarm | Select BuildVersion

Change SharePoint Site Title and description using PowerShell

Below is the PowerShell script to change the SharePoint 2013/2016 site title and description using PowerShell script. By using PowerShell you can change the title and description easily.

$Web= Get-SPWeb "http://SiteURL"
$Web.Title = "My New Portal"
$Web.Description = "This is our new portal"
$web.Update()

After you execute the PowerShell script, the site title and description will get changed.

Attach event receivers to SharePoint list using PowerShell

This SharePoint PowerShell example explains, how to attach an event receiver to SharePoint 2013/2010 list using PowerShell. Here I will show how we can attach an event receiver to a SharePoint list in SharePoint 2010/2013.

PS > $spWeb = Get-SPWeb http://siteurl
PS > $spList = $spWeb.Lists[“Tasks”]
PS > $spEvent.Name = “My Event”
PS > $spEvent.Type = “ItemAdded”
PS > $spEvent.Synchronization = “Asynchronous”
PS > $spEvent.SequenceNumber = 3000
PS > $spEvent.Assembly = “My.SharePoint.Event, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a8b0a959bb9389c6”
PS > $spEvent.Class = “My.SharePoint.Event.PowerShellEventReceiver”
PS > $spEvent.Update()
PS > $spWeb.Dispose()

The above code explains, how to attach an event receiver to SharePoint 2010 list using PowerShell.

Change SharePoint list Settings using PowerShell

We will see now how we can change SharePoint list settings using PowerShell. Through PowerShell, you can change SharePoint list title, description, whether a version will be enabled or not etc.

#Get the site and list objects

$web = Get-SPWeb http://entersiteurl
$list = $web.Lists[“Shared Documents”] // Enter the name of list.

#Now enter the changes what you want

$list.Title = “Enter Title Name”
$list.Description = “Enter Description”
$list.OnQuickLaunch = $true
$list.EnableModeration = $true //Enable content Approval
$list.EnableVersioning = $true //Enable the versioning

#Update the list and dispose of the web object

$list.Update()
$web.Dispose()

Show hide Workflow History list using PowerShell in SharePoint 2013/2010

Now we will see how to show hide workflow history list using PowerShell in SharePoint 2016/2013/2010. Sometimes you will not get the “Workflow History” list which appears to be hidden.

So below is the PowerShell command, once you will execute this the “Workflow History” list will appear.

$web = Get-SPWeb “http://WebURL”
$list = $web.Lists[“Workflow History”]
$list.Hidden = $false
$list.Update()

Get System Accounts using PowerShell

Now we will see how to get all system accounts using PowerShell in SharePoint 2010. PowerShell is very much improved as compared to STSADM.

SPProcessAccount helps us to get all the system accounts like LocalSystem account, LocalService account and NetworkService account.

Get-SPProcessAccount:
This command will retrieve all the above accounts.
But if you want to retrieve indivisually then we have to follow below commands:

LocalSystem account:
Get-SPProcessAccount –LocalSystem

LocalService account:
Get-SPProcessAccount -LocalService

NetworkService account:
Get-SPProcessAccount –NetworkService

PowerShell Command to Create a new Web Application in SharePoint 2016/2013/2010

Now we will discuss how to create a web application in SharePoint 2010/2013/2016 using PowerShell. SPWebApplication is responsible for creating a new web application in PowerShell.

New-SPWebApplication –applicationpool <Application pool name> -name <Web app name> -applicationpoolaccount <service account for the application pool> -port <port number>

Example:
New-SPWebApplication –applicationpool SharePoint-80 -name SharePoint-80 -applicationpoolaccount SP2010\Administrator -port 80

PowerShell Command to Create a New Site Collection (Top Level Site)

Now, we will discuss how can we create a new site collection using PowerShell in SharePoint 2010/2013/20166

New-SPSite is responsible for creating a new site collection.

New-SPSite –url <full url of new site collection>
-name <name of new site collection>
-owneralias <site collection administrator>
-template <site collection template to use>

Example:
New-SPSite –url http://enjoysharepoint/ -name Home -owneralias SP2010\Administrator -template STS#0

PowerShell Command to Create a New Sub Site in SharePoint

Now, we will discuss how to create a new sub site in SharePoint using PowerShell. SPWeb is responsible for creating a sub site.

New-SPWeb –url <full url of new site> -name <name of new sub site> -template <site template to use>

Example:
New-SPWeb –url http://enjoysharepoint/TestSubSite -name “Test Sub Site” -template STS#0

Below are few PowerShell command:

  • Get-command : To see PowerShell commands in the window.
  • Get-command SP : Show all commands that contain word SP.
  • Get-command -SP > c:\spcommands .txt: Will save all commands to a text file, those commands contains the word SP.
  • get-help : Give some suggestion. When we need help.
  • Get-SPWebApplication : Information about the web application. It will display the list of all web applications and its display name and URL of the web application.
  • Get-SPSite : Returns lists of all the site collectios’ URL.
  • Get-SPDatabase : Show list of all SharePoint Database Name, ID and Type.
  • Set-SPSite -Identity http://Site-Collection-URL -MaxSize 500MB: Limits the size of the site collection

Backup and restore site collection using PowerShell in SharePoint 2010/2013/2016

Now we will discuss how to backup and restore a site collection using PowerShell in SharePoint 2010/2013/2016.

Backup a SharePoint Site collection with PowerShell command

Backup-SPSite -Identity http://myserver -Path “c:\backup\file.bak”

Restore a SharePoint Site Collection with PowerShell command

To restore site collection you’ll use the following command. Use –Force if you want to overwrite the existing site collection

Restore-SPSite -Identity http://myserver -Path “c:\backup\file.bak”

Download a wsp file from SharePoint using PowerShell

We can able to download a particular wsp file from SharePoint central admin using PowerShell. There is no direct approach to download a wsp file from Central Administration. You will only see the option to Retract a solution file.

Below is the PowerShell command to dowload a solution (wsp) file:

$farm = Get-SPFarm
$file = $farm.Solutions.Item(“MyTest.wsp”).SolutionFile
$file.SaveAs(“c:\MyTest.wsp”)

Remember to run the above PowerShell command you need to be a member of the Farm Administrators group and have permission to the configuration database.

Change SharePoint site logo using PowerShell

Now we will see, how we can change the SharePoint 2010/2013/2016 site logo using PowerShell.

SharePoint 2010/2013 site default logo comes from the _layouts/images/ folder.

If you want to put your new logo then you can put your logo to a folder where you have read access. Also, you can put your logo to Assets Library also.

Below is the PowerShell script to change site logo in SharePoint

$web = Get-SPWeb “http://SiteURL”
$web.SiteLogoUrl = “http://Path of the image file”
$web.SiteLogoDescription = “EnjoySharePoint.com company Logo”
$web.Update()

After this refresh the SharePoint page, the new logo should appear.

Delete an application pool using PowerShell in SharePoint

Here we will discuss how we can delete an application pool using PowerShell in SharePoint.

PowerShell is the best way to remove an application pool for SharePoint. Sometimes you may need to remove unused application pool accounts.

Open SharePoint management PowerShell, Make sure you are running as administrator mode.

Run the below command which will display all the application pools.

Get-SPServiceApplicationPool

Then run the below command to get the particular Application Pool.

Get-SPServiceApplicationPool -Identity <Name of the application pool>

Now we can to delete whatever the application pool we want.

Remove-SPServiceApplicationPool ‘Name of the Application Pool’

The above PowerShell command will delete the application Pool.

Approve master page using PowerShell in SharePoint 2010/2013/2016

Now we will see how to approve a modified master page using PowerShell in SharePoint 2010/2013/2016.

Sometimes SharePoint gives some error when you try to commit the master page which you have edited using SharePoint designer 2013/2010. In that case, you can use the PowerShell to approve the master page.

The following PowerShell Script will help you to approve the master page in SharePoint.

Open SharePoint 2010/2013/2016 management PowerShell, Make sure you are running as administrator mode.

$SPWeb = Get-SPWeb “http://SiteURL”
$file = $SPWeb.GetFile(“_catalogs/masterpage/MyCustomMaster.master”)
$file.CheckIn(“”)
$file.Publish()

The above PowerShell script will approve master page in SharePoint.

Prevent delete of SharePoint list using PowerShell

We can also restrict the user to delete a particular SharePoint list using PowerShell in SharePoint 2013/2016. We can prevent delete option in SharePoint list by using PowerShell.

$web = Get-SPWeb “http://SiteURL””
$list = $web.Lists[“My Custom List”]
$List.AllowDeletion=$false
$List.Update()

Once you execute this PowerShell code, you can not delete the list.

PowerShell commands for scheduling user profile timer job in SharePoint

We can use PowerShell command for scheduling user profile timer job in SharePoint 2013/2016.

Powershell command to schedule user profile timer job

Get-SPTimerJob is used to return timer jobs.

Get-SPTimerJob returns all the timer jobs with Name, Schedule, and Last Run.

Get-SPTimerJob UserProfile_ProfileImportJob | Set-SPTimerJob -Schedule “weekly between sun 12:00:00 and wed 12:00:00” | Start-SPTimerJob

Schedule:
Specifies the schedule for running the timer job.

The type must be a valid SharePoint Timer service (SPTimer) schedule in the form of any one of the following schedules:

Every 5 minutes between 0 and 59
Hourly between 0 and 59
Daily at 15:00:00
Weekly between Fri 22:00:00 and Sun 06:00:00
Monthly at 15 15:00:00
Yearly at Jan 1 15:00:00

You may like following PowerShell SharePoint tutorials:

This PowerShell SharePoint explains, how can we undo check out a page using PowerShell Script, How to change Page Layout using PowerShell Script in SharePoint.

Also, we will see how to Extract wsp from SharePoint Farm Solutions using PowerShell and PowerShell script to empty SharePoint Recycle Bins.

We will also see how to collect ULS logs for specific CorrelationID in SharePoint 2016/2013 using PowerShell. PowerShell Script to Export Site into Excel file, PowerShell to get installed SharePoint Version Number.

Check out Best Alternative to InfoPath -> Try Now

EnjoySharePoint YouTube Channel

You May Also like the Following SharePoint Tutorials:

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →