50+ PowerShell SharePoint Examples

In this PowerShell SharePoint tutorial, we will discuss a 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 the PowerShell script to empty SharePoint Recycle Bins and how to collect ULS logs for specific CorrelationID in SharePoint 2016/2013 using PowerShell.

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

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

Table of Contents

SharePoint: Undo check out a page using PowerShell Script

This example explains how to undo check out a page using the PowerShell script in SharePoint. Recently we face one issue in one of the migration projects.

Some pages were coming to check out by some people and when we try to do a 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()

How to Change Page Layout using PowerShell Script

In this example, we will discuss how we can change a page layout using a PowerShell 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

Below is the PowerShell script to change the 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

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 2019/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.

Read PowerShell read all files from folder and subfolder

PowerShell script to empty SharePoint Recycle Bins

Now, we will see the 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

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 site title and description using the 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.

Read How to upload files to SharePoint using PowerShell

Change SharePoint list Settings using PowerShell

We will see now how to change SharePoint list settings using PowerShell. Through PowerShell, you can change the 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

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 of the above accounts.
But if you want to retrieve individually then we have to follow the below commands:

LocalSystem account:

Get-SPProcessAccount –LocalSystem

LocalService account:

Get-SPProcessAccount -LocalService

NetworkService account:

Get-SPProcessAccount –NetworkService

Read PowerShell SharePoint list operations

Create a new SharePoint Web Application using PowerShell

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.

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 subsite in SharePoint using PowerShell. SPWeb is responsible for creating a subsite.

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 a few PowerShell commands:

  • 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

Read PowerShell SharePoint site collection example

Backup and restore site collection using PowerShell in SharePoint

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 download 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 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 the Assets Library also.

Below is the PowerShell script to change the 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.

Read How to Change SharePoint Site Logo

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 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

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 that you have edited using SharePoint Designer. In that case, you can use PowerShell to approve the master page.

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

Open SharePoint 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 the master page in SharePoint.

Read Display warning message in SharePoint site using PowerShell

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 the delete option in the 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 the 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:
Specify 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

PowerShell commands for SharePoint database

This SharePoint tutorial explains various PowerShell commands for the SharePoint database. We will see how to retrieve all databases, get a particular web application, create a new content database, etc. Below are PowerShell Commands to see all databases.

Get-SPDatabase

The above command will return all databases.

If you want to retrieve a particular database then follow below command:
Get-SPDatabase-Identity

The cmdlet to get all the web applications:

Get-SPWebApplication

PowerShell Command to create new content database:

New-SPContentDatabase –Name ContentDBName –WebApplication “Web Application URL”

PowerShell Cmdlet to retrieve all content database for a particular web application:

Get-SPContentDatabase –WebApplication “Web Application URL”

Get-SPContentDatabase –WebApplication “http://bsahoo3:2600/”

PowerShell Cmdlets to Attach a Content Database to a Web Application:

Mount-SPContentDatabase –Name “ContentDBName” –WebApplication “Web Application URL”

PowerShell Cmdlet to Delete a Content Database:

Remove-SPContentDatabase “ContentDBName”

PowerShell Cmdlet to Create a New Configuration Database:

New-SPConfigurationDatabase –DatabaseName NewConfigurationDBName –DatabaseServer “Database Server name”

PowerShell Cmdlet to Delete a Configuration Database:

Remove-SPConfigurationDatabase

This command will delete the current configuration database.

PowerShell Cmdlet to take backup of a configuration database:

Backup-SPConfigurationDatabase –Directory C:\DatabaseBackUp

PowerShell Cmdlet to take restore of a configuration database:

Restore-SPFarm –Directory C:\DatabaseBackUp

PowerShell Cmdlet to Back Up the SharePoint Farm:

Backup-SPFarm –BackupMethod Full –Directory C:\FarmBackup

Full means it will take backup of the entire farm.

PowerShell Cmdlet to Restore the SharePoint Farm:

Restore-SPFarm –Directory C:\FarmBackup –RestoreMethod Overwrite

PowerShell Cmdlet to Back Up a Site Collection:

Backup-SPSite –Identity “http://Site Collection URL”–Path C:\SiteCollectionBackup\MySiteCollection.bak

PowerShell Cmdlet to Restore a Site Collection

Restore-SPSite –Identity “http://Site Collection URL”–Path C:\SiteCollectionBackup\MySiteCollection.bak –Force

Force will overwrite the existing site collection.

Read How to Get SharePoint site template PowerShell

PowerShell to know site created date SharePoint

Below are the PowerShell commands to know the site created date in SharePoint 2013/2016/2010.

PowerShell command to get all site collections created date

Below is the PowerShell command to get all sites collections created date in SharePoint.

Add-PSSnapin “Microsoft.SharePoint.PowerShell”
Get-SPSite -Limit All | select Url, {$_.RootWeb.Created}

PowerShell command which will give Sites and Subsites created in the last 30 days

Below is the PowerShell command or script which will give sites and subsites created in the last 30 days.

Add-PSSnapin “Microsoft.SharePoint.PowerShell”
$Today = [DateTime]::Today
$Before30Days = $Today.AddDays(-30)
Get-SPSite -Limit All | where {$_.RootWeb.Created -ge $Before30Days -And $_.RootWeb.Created -lt $Today} |
select Url, {$_.RootWeb.Created}

PowerShell command which will return sites created Today

Below is the PowerShell command which will return sites that are created today in SharePoint 2013.

Add-PSSnapin “Microsoft.SharePoint.PowerShell”
$Today = [DateTime]::Today
Get-SPSite -Limit All | where {$_.RootWeb.Created -eq $Today} |
select Url, {$_.RootWeb.Created}

PowerShell command which will return sites and subsites created date for a Particular site collection

Below is the PowerShell command which will return sites and subsites created date for a particular site collection.

Add-PSSnapin “Microsoft.SharePoint.PowerShell”
$site = get-spsite https://SiteCollectionURL/
$webs = $site.allwebs
foreach ($w in $webs){Write-Host $w.title ” is created on ” $w.created}

How to set a custom page as homepage using PowerShell in SharePoint 2010/2013

We can set my newly created custom page in my SharePoint site as the home page. It’s possible to use a custom page as a home page. You can set it in multiple ways: If you have enabled the Publishing features on your site, or your site was created from a Publishing template, then you can just go to Site Actions, Site Settings, and click Welcome Page, then select a page.

You can open the site in SharePoint Designer, right-click any .ASPX page, and select Set as Home Page.

If you’re a developer, you can set the home page by using the code. See the MSDN page “SPFolder.WelcomePage property” for more information.

If you’re a SharePoint administrator, you can use a Windows PowerShell script to select a master page:

$site = Get-SPSite http://yourserver/sites/yoursite
$web = $site.RootWeb
(or $web = $site.OpenWeb(“yoursubsite”)
$folder = $web.RootFolder
$folder.WelcomePage = “SitePages/home.aspx”
(or $folder.WelcomePage = “default.aspx”)
(or $folder.WelcomePage = “Shared%20Documents/mycustomwebpartpage.aspx”)
$folder.update()
$web.Dispose()
$site.Dispose()

Read How to get file modification time and date using PowerShell

Get SharePoint feature details from Feature ID or Display Name using PowerShell

Now, we will see how we to get SharePoint feature details based on FeatureID and also by using Feature DisplayName using PowerShell in SharePoint 2013/2016.

Sometimes you may need to know about the feature details based on the feature Id in SharePoint

PowerShell command to get feature details based on SharePoint feature id

Below is the PowerShell command to get the feature details based on feature id in SharePoint 2013/2016.

Add-PSSnapin "Microsoft.SharePoint.PowerShell"
Get-SPFeature -Limit ALL | Where-Object {$_.id -eq "22a9ef51-737b-4ff2-9346-694633fe4416"}
Get SharePoint 2013 feature details from Feature ID or Display Name using PowerShell
Get SharePoint 2013 feature details from Feature ID or Display Name using PowerShell

PowerShell command to get feature details based on feature display name in SharePoint

Below is the PowerShell command to get the SharePoint feature details based on the feature display name.

Add-PSSnapin "Microsoft.SharePoint.PowerShell"
Get-SPFeature -Limit ALL | Where-Object {$_.DisplayName -eq "Publishing"}

Retrieve all site collections under particular content databases using PowerShell

In this example, we will see how to retrieve all site collections under a particular content database programmatically using PowerShell in SharePoint 2013/2016.

Here I have a content database name as: WSS_Content_808ab8b0aa0b4298bd1e626628caa80d

Write the below command to get all the site collections presented in the content database:

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
Get-SPSite -ContentDatabase "WSS_Content_808ab8b0aa0b4298bd1e626628caa80d"

If you want to retrieve in csv or text format then you can write the below:

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
Get-SPSite -ContentDatabase "WSS_Content_808ab8b0aa0b4298bd1e626628caa80d"> E:\AllSites.txt

Or

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA SilentlyContinue
Get-SPSite -ContentDatabase "WSS_Content_808ab8b0aa0b4298bd1e626628caa80d"> E:\AllSites.csv

Once you run the above command you can see all site collections like below:

Retrieve all site collections under particular content databases using PowerShell

Read How to remove SharePoint Online Modern Page Title using PowerShell

Insert bulk items to SharePoint Online list using PowerShell

In this PowerShell SharePoint example, we will discuss how to insert bulk items to a SharePoint Online list using PowerShell.

Here I have a list as “Laptop” and by using PowerShell we will insert 5000 items to the SharePoint Online list.

Add-Type -Path 'C:\Users\Admin\Desktop\Microsoft.SharePoint.Client.dll'
Add-Type -Path 'C:\Users\Admin\Desktop\Microsoft.SharePoint.Client.Runtime.dll'

$SiteURL = "https://<tenantname>.sharepoint.com/sites/LaptopCompany/"
$listName="Laptop"
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$securePassword=ConvertTo-SecureString "[email protected]" -AsPlainText -Force
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials("anjaline@<tenantname>.onmicrosoft.com", $securePassword)
$web = $ctx.Web
$list = $web.get_lists().getByTitle($listName)
for ($i=1; $i -le 5001; $i++)
{
$itemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$listItem = $list.addItem($itemCreateInfo)
$listItem.set_item('Title', 'Laptop Request')
$listItem.set_item('LaptopName', 'Hp')
$listItem.set_item('Price', '20000')
$listItem.update();
$ctx.Load($listItem)
$ctx.ExecuteQuery()
}

Once you run the above PowerShell cmdlets, it will insert 5000 items to the SharePoint Online list.

Get a list of pages using a particular page layout using PowerShell in SharePoint 2013

In this SharePoint PowerShell example, we will see, how to get a list of pages that are using a particular page layout in SharePoint 2013 using PowerShell.

Recently while working on a moss 2007 to SharePoint 2013 migration project we got a scenario where we need to find out the page names from a document library that is using a particular page layout in SharePoint 2013/2016.

Below is the PowerShell script to get the list of pages using a particular page layout using PowerShell in SharePoint 2013.

Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$site = get-SPSite http://win-pfcp2dgt8di/sites/EnjoySharePoint/
$web = $site.RootWeb
$pweb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
$pPages = $pWeb.GetPublishingPages();
$pLayouts ="ErrorLayout.aspx" #$pweb.GetAvailablePageLayouts()
foreach ($pPage in $pPages)
{
if ($pPage.Layout.Name -eq $pLayouts)
{
write-host $pPage.Title
}
}

This PowerShell example helps to learn, how to get a list of pages using a particular page layout using PowerShell in SharePoint 2013/2016.

Read How to activate SharePoint Publishing Feature Programmatically using CSOM and PowerShell

Get all content types from site collection using PowerShell in SharePoint

In this example, we will see how to get all the content types from site collection using PowerShell in SharePoint 2013 or SharePoint 2016

Below is the PowerShell command which will give you all the content types from site collection in SharePoint 2013.

Add-PSSnapin “Microsoft.SharePoint.PowerShell”
$site = Get-SPSite http://win-pfcp2dgt8di/sites/EnjoySharePoint/
$web = $site.RootWeb
foreach ($ctype in $web.ContentTypes) {$ctype | Format-Table ID,Name -AutoSize}

The output will look like below:

Get all content types from site collection using PowerShell in SharePoint

Get SharePoint Feature IDs using PowerShell in SharePoint

This PowerShell SharePoint tutorial explains, how we can retrieve feature IDs in SharePoint by using PowerShell. The PowerShell script has been tested for the SharePoint 2010 version.

So if you want to retrieve in SharePoint 2013, SharePoint 2016, or SharePoint 2019, you have to change the folder page like here for SharePoint I have added 14 hive path.

Retrieve Feature ID using PowerShell: Use the below PowerShell script to get the feature ID, Title, and Scope.

You can write the PowerShell script using Visual studio code or Windows PowerShell ISE.

$results=Get-ChildItem "c:\\Program Files\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\FEATURES\" feature.xml -rec

foreach ($File in $results)
{
[xml]$feat=gc $file.pspath
$feat.feature | Select ID, Title, Scope
}

Hopefully, the above script will work for you and you can get feature id in SharePoint 2010/2013/2016/2019.

Read The file is not digitally signed PowerShell script

Copy data from one column to another column within SharePoint list using PowerShell

Now, we will see how to copy data from one column to another column within SharePoint 2010/2013/2016.

PowerShell script for copy data from one column to another column within the SharePoint list:

Add-PSSnapin Microsoft.Sharepoint.Powershell
[System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$site = new-object Microsoft.SharePoint.SPSite("SiteURL")
$web = Get-SPWeb -Identity siteURL
$lista =$web.Lists["ListName"]
$items = $lista.items
foreach ($item in $items) {
$user = $item["Source column"]
write-host $useracc
$useracc = $web.EnsureUser( $user);
$item["Desination column"] = $useracc
write-host $useracc
$item.update()
}
$lista.update()

Here, we checked how to copy data from one column to another column within SharePoint 2013/2016/2010 list using PowerShell.

Reset SharePoint Farm Passphrase password using Powershell

Now, we will see how to reset the SharePoint farm Passphrase password using Powershell. SharePoint allows us to set passphrase at the time of installation.

The passphrase is used to secure farm communications and will have to be provided by any additional servers joining the farm.

If you forget that password then you can reset or change the passphrase. There is no option you can retrieve the passphrase.

But you should choose a reasonably strong passphrase and document it in a safe place.

Login to the Sharepoint server with your Farm Account(should have permission to Sharepoint Config DB). Start > All Programs > Microsoft SharePoint 2010 Products > SharePoint 2010 Management Shell and make sure you Run As Administrator.

Then enter the below thing in PowerShell prompt:

$passphrase = ConvertTo-SecureString -asPlainText –Force

Then enter the new Passphrase and hit enter. Then enter the below in the command prompt.

Set-SPPassPhrase -PassPhrase $passphrase -Confirm

You will be asked to confirm the passphrase by re-entering it. Re-enter the passphrase and hit Enter

Issue the following command and follow the onscreen instructions (essentially, it will ask you to confirm the passphrase and press ‘Y’

Now your SharePoint farm passphrase should be reset.

Read Get SharePoint List Name and GUID using PowerShell and CSOM

Remove Extended Zone using PowerShell in SharePoint 2013

Now, we will see how to remove the Extended Zone using PowerShell in SharePoint 2013.

Here we will remove the intranet zone using this PowerShell command.

Get-SPWebApplication http://webapplicationurl | Remove-SPWebApplication -Zone "Intranet"

If the error message happens like below given the message —

“Remove-SPWebApplication : An object of the type Microsoft.SharePoint.Administration.SPIisWebsiteUnprovisioningJobDefinition named “Unprovisioning SecretZone” already exists under the parent Microsoft.SharePoint.Administration.SPWebService named “”. Rename your object or delete the existing object.
At line:1 char:24

  • Remove-SPWebApplication <<<< http://webapplicationurl -Zone “intranet”
  • CategoryInfo : InvalidData: (Microsoft.Share…PWebApplication:
    SPCmdletRemoveSPWebApplication) [Remove-SPWebApplication], SPDuplicateObjectException
  • FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletRemoveSPWebApplication”

Resolve this error using these Steps:

Go to SharePoint 2013 Central Administration, then Click on Monitoring link and Go to Review job definition’s.

Now Scroll to the bottom and click the forward arrow and now you look for “Unprovisioning web application”, Now you delete it.

Make SharePoint List Column non-editable in SharePoint using PowerShell

Now, we will see how to make the SharePoint field or list column non-editable using PowerShell. The PowerShell script will work to make a list column read-only in SharePoint 2010/2013/2016.

First, we create a list and add the column Name as a text with calculating the value. See in fig

make sharepoint list column readonly using powershell

Now I want this Name Column non-editable. So we use the PowerShell script for this.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Getting the Web
$web = Get-SPWeb “http://test:7070/”
#Getting the List
$List = $Web.Lists[“TesetReadOnly”]
#Getting the Field
$Field = $List.Fields[“Name”]
#Setting the field to Read only
$Field.ReadOnlyField = $true
$Field.Update()

Now you see the Name column is noneditable (not showing in your form new/edit/display) that’s value take calculated or default. See in fig

make sharepoint list column non editable using powershell

After Saving the item Name field value take as a calculated. See in fig

make sharepoint 2010 list column readonly using powershell

This way, we can make a SharePoint list column or field read-only using PowerShell.

Read Connect to SharePoint Online Site using PowerShell

Force UndoCheckout or checkin using PowerShell in SharePoint 2013

Now, let us see how to forcefully UndoCheckOut a page using PowerShell in SharePoint 2013. Sometimes when you will try using a browser you will not be able to UndoCheckout a page. In that case, PowerShell will be very much helpful.

Below is the PowerShell command to UndoCheckOut default.aspx page from Pages document library.

Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$targetWeb = "https://SiteURL"
$targetLibrary = "Pages"
$fileName = "default.aspx"
$myWeb = Get-SPWeb $targetWeb
$myLib = $myWeb.GetFolder($targetLibrary)
$myFile = $myLib.Files | ? {$_.name -eq $fileName}
$myFile.UndoCheckOut()
$myFile.Update()

Also, you can use the below PowerShell command:

$web = Get-SPWeb https://SiteURL
$list = $web.Lists["Pages"] $file = $list.GetItemById(1); // ID of the file with the issue
$file.File.UndoCheckout()
$file.File.Checkin("")

You can check the item id from the Pages document library from the SharePoint document library.

Get SharePoint installed build version using PowerShell

Now, we will see how to get SharePoint installed build version using PowerShell as well as we will see how to get build version in SharePoint online.

Below is the PowerShell command to get build version in on-premise:

Add-PSSnapin “Microsoft.SharePoint.PowerShell”
get-spfarm | select BuildVersion

It will display like below:

Get SharePoint installed build version using PowerShell

To get the build version in SharePoint online we have to browse the _vti_pvt/buildversion.cnf URL.

In my SharePoint Online site it should be like this:

https://onlysharepoint2013.sharepoint.com/_vti_pvt/buildversion.cnf

And it will display like below:

Get SharePoint online installed build version using PowerShell

Read Delete content type from SharePoint list using PowerShell

Get all Sites and Subsites under Site Collection using PowerShell in SharePoint

Now, we will see how to get all sites and subsites under a site collection using PowerShell in SharePoint 2013/2016.

Below is the PowerShell command to get all Sites and Subsites under a SharePoint Site Collection.

$Site="http://win-pfcp2dgt8di/sites/EnjoySharePoint/"
$Sites=new-object Microsoft.SharePoint.SPSite($Site)
foreach($web in $Sites.Allwebs){
Write-Host($web.Url)
$web.Update()}
$Sites.Dispose()

I have used the PowerShell script in the Windows PowerShell ISE and for this, I have just added the below line at the beginning:

Else you will get the error like below:
Cannot find type [Microsoft.SharePoint.SPSite]: make sure the assembly containing this type is loaded.

The PowerShell script looks like below, which will retrieve all the sites and subsites under a site collection in SharePoint 2013.

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$Site="http://win-pfcp2dgt8di/sites/EnjoySharePoint/"
$Sites=new-object Microsoft.SharePoint.SPSite($Site)
foreach($web in $Sites.Allwebs){
Write-Host($web.Url)
$web.Update()}
$Sites.Dispose()
Get all Sites and Subsites under Site Collection using PowerShell

Disable ViewFormPagesLockdown feature in SharePoint using PowerShell

ViewFormPagesLockdown is a hidden feature, by default this feature got activated in the publishing site but not in team site definitions.

This feature allows users to view publishing pages, not to any form pages like DispForm.aspx or AllItems.aspx pages.

Also, this feature does not allow anonymous access to pages in the _layouts directory that inherit from LayoutsPageBase.

If you want to check whether ViewFormPagesLockdown feature is already activated or not, then you can run the below PowerShell command.

Get-SPFeature | where { $_.DisplayName -eq "ViewFormPagesLockdown"}

If its already activated, then it will show the scope, display name as well as the ID.

If you want to disable ViewFormPagesLockdown feature, then you can use the following PowerShell command:

$lockdown = get-spfeature viewformpageslockdown
disable-spfeature $lockdown -url http://sitecollectionURL

Read How to perform IIS backup and restore using PowerShell

Hide custom feature from UI in SharePoint using PowerShell

There might have some situations where you do not want to show your custom features in SharePoint UI and allow farm administrators to activate the feature through PowerShell.

Here we will discuss how we can hide a feature from UI and how to activate a hidden feature using PowerShell.

Hide A Feature:
Remember if you hide a feature then st it is not available for activation from UI. Only farm administrators/site collection administrators can activate the feature through PowerShell.

To hide a feature Open the features Template.xml file (using Visual Studio) and then Add an attribute Hidden=True in feature tag.

It should look like this:

<feature xmlns="http://schemas.microsoft.com/sharepoint/" Title="My Feature" Hidden="TRUE">

Activate Hidden Feature Through PowerShell:

The hidden feature can be activated by using PowerShell.

First, get all the features to get the Name or GUID of the feature which you want to activate.

Get-SPFeature -Limit ALL | Where-Object {$_.Hidden -eq $true -and $_.Scope -eq "WEB"} | Sort-Object DisplayName | Select DisplayName,Id

You can also run below PowerShell Command:

Get-SPFeature | where {$_.Hidden -eq "True" -and $_.Scope -eq "Web"}

Once you get the GUID in the above command you can use the below command to activate the feature.

Enable-SPFeature -identity "<GUID>" -url "<Web/Site URL(depending on the Scope)>"

This is how we can hide custom feature from UI in SharePoint 2010 or SharePoint 2013 using PowerShell.

Read How to use PnP PowerShell in SharePoint Online

Deploy new version webpart from old webpart in SharePoint using PowerShell

Now we will discuss, how to deploy a new version web part from old web part in SharePoint server 2010.

I want to upload a new version of the web part in the SharePoint Site collection in replacing my old web part. In this web part, I added some advanced functionality and I create the .wsp file from visual studio 2010 as the same old web part.

Please remember when you added the functionality in your old web part you should use an old solution where you create your old web part in visual studio 2010. No need for a new solution or new web part.

You just open your old web part or solution in visual studio 2010 and add the new functionality. And also remember you don’t deploy the web part just add the functionality and after this create the new .wsp file and follow these steps:

Open PowerShell command and run the following command:

Update-SPSolution –Identity ApplicationWebpart.wsp –LiteralPath C:\WebPart\ForUpgrade\Update\ApplicationWebpart.wsp –GACDeployment

After this, you activate the feature in your site collection.

Now you are able to see the new functionality in your web part.

Using this we don’t lose our data from the old web part we are able to see old data with new functionality.

Find larger files inside web application in SharePoint using PowerShell

Now, let us see how to find larger files within a web application in SharePoint using PowerShell.

Below is the PowerShell script to get files that are more than 500 MB inside a web application in SharePoint 2010 or SharePoint 2013/2016.

cls
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null)
{
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
Start-SPAssignment -Global
#Change the site url below
$Site = Get-SPSite http://SiteURL/
$spWeb = $Site.WebApplication
#Enter the target file size in MB
$fileSize = 50
[string]$fileUrl
Write-Host "——Checking the SP web app for large files——"
# Enumerate though all site collections, sites, sub sites and document libraries in a SP web app
if($spWeb -ne $null)
{
foreach ($siteColl in $spWeb.Sites)
{
foreach($subWeb in $siteColl.AllWebs)
{
foreach($List in $subWeb.Lists)
{
if($List.BaseType -eq "DocumentLibrary")
{
$ItemsColl = $List.Items
foreach ($item in $ItemsColl)
{
$itemSize = (($item.File.Length)/1024)/1024
if($itemSize -Ge $fileSize)
{
$itemUrl = $item.Web.Url + "/" + $item.Url;
Write-Host $itemUrl ", File size:: " $('{0:N2}' -f $itemSize) MB -ForegroundColor Green
}
}
}
}
}
}
}
Write-Host "———DONE———"
Stop-SPAssignment -Global

This is how to get files that are more than 500 MB inside a web application in SharePoint 2010 or SharePoint 2013/2016 using PowerShell.

Read How to deploy WSP Solution in SharePoint using PowerShell

PowerShell script to get all list with lookup columns in SharePoint

Now. let us see how to get all lists with lookup columns in SharePoint 2013/2016/2010 using PowerShell.

When you are working on the migration project it’s very important to have a list of lookup columns as sometimes lookup column migration doesn’t happen through the tool. There could be many other requirements where you need to extract the lookup column of your site.

We had extracted lookup column details for the entire farm. So let’s script it. Sharing the code snippet to get the lookup column, respective list name, web URL.

PowerShell script to get all list with lookup columns in SharePoint

Below is the PowerShell script to get all lists with lookup columns in SharePoint.

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
try{
#Create a variable based on the current date and time
$StartTime = (Get-Date -UFormat "%Y-%m-%d_%I-%M-%S %p").tostring()

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$output = $("$dp0\Result\ListsWithLookupColumns_" +$StartTime +".csv")

$logFile=$("$dp0\Logs\ListsWithLookupColumnsLog.txt")
Write "Script started running at " $StartTime >> $logFile

##Creating and Returning a DataTable##
function createDT()
{
###Creating a new DataTable###
$tempTable = New-Object System.Data.DataTable

##Creating Columns for DataTable##
$col1 = New-Object System.Data.DataColumn("URL")
$col2 = New-Object System.Data.DataColumn("List Name")
$col3 = New-Object System.Data.DataColumn("Field Name")

###Adding Columns for DataTable###
$tempTable.columns.Add($col1)
$tempTable.columns.Add($col2)
$tempTable.columns.Add($col3)

return ,$tempTable
}
[System.Data.DataTable]$dTable = createDT

#Initialize Workflow Count variable
$TTNExcludeLists = "Solution Gallery",
"Master Page Gallery"

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$websvcs = $farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.SharePoint.Administration.SPWebService]}
foreach ($websvc in $websvcs)
{
try
{
foreach ($webApplication in $websvc.WebApplications)
{
try
{
Write "`r`n Inside the loop for web application" $webApplication.Url >> $logFile
foreach($site in $webApplication.Sites)
{
try
{
Write "`r`n Inside the loop for site" $site.Url >> $logFile
foreach($web in $site.AllWebs)
{

Write "`r`n Inside the loop for web" $web.Url >> $logFile
foreach($list in $web.Lists)
{
Write "`r`n Inside the loop for the list" $list.Title >> $logFile
if(-Not ($TTNExcludeLists -Contains $list.Title))
{
foreach($fld in $list.Fields)
{
if($fld.TypeDisplayName -eq "Lookup" -and $fld.Hidden -eq $false -and $fld.FromBaseType -eq $false)
{
Write-Host "web URL: " $web.Url "ListName: " $list.Title "FeildName: " $fld.Title
$row = $dTable.NewRow()
$row["URL"] = $web.Url
$row["List Name"] = $list.Title
$row["Field Name"] = $fld.Title

$dTable.rows.Add($row)
}

}
}
}
$web.Dispose()
}
}
catch [Exception]{
Write $_.Exception|format-list -force >>$logFile
Write-Host -f red $_.Exception|format-list -force
}
finally{
if($web){
$web.Dispose()
}
}

$site.Dispose()

}
}
catch [Exception]{
Write $_.Exception|format-list -force >>$logFile
Write-Host -f red $_.Exception|format-list -force
}
finally{
if($site){
$site.Dispose();
}
}

}
}
catch [Exception]{
Write $_.Exception|format-list -force >>$logFile
Write-Host -f red $_.Exception|format-list -force
}
}

if($dTable -ne $null)
{
$dTable | Export-CSV -path $output -notype
#Write-Host "Done" -ForegroundColor Green
}
else
{
Write-Host "Could not write anything to table" -ForegroundColor red
}
}
catch [Exception]{
Write $_.Exception|format-list -force >>$logFile
Write-Host -f red $_.Exception|format-list -force
}
$EndTime = (Get-Date -UFormat "%Y-%m-%d_%I-%M-%S %p").tostring()
Write "Script stopped at" $EndTime >> $logFile

Extract term store in SharePoint using PowerShell

Now, let us see, how to extract term store data in SharePoint 2013/2016 using PowerShell.

Have u created a term store in the SharePoint environment and want to extract it for business user review or trying to move the terms to different environments. So let’s write a PowerShell script to extract the term store data.

Make sure you create a folder named as Result and Log file inside the same folder where you are keeping the ps file

PowerShell Script to extract term store in SharePoint

Below is the full PowerShell script which you can write, test and debug using PowerShell ISE.

if((Get-PSSnapin ‘Microsoft.SharePoint.PowerShell’ -ErrorAction SilentlyContinue) -eq $null){Add-PSSnapin ‘Microsoft.SharePoint.PowerShell’}
try{
#Create a variable based on the current date and time
$StartTime = (Get-Date -UFormat “%Y-%m-%d_%I-%M-%S %p”).tostring()

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$output = $(“$dp0\Result\TaxonomiesInformationReport_” +$StartTime +”.csv”)

$logFile=$(“$dp0\Logs\TaxonomiesInformationLog.txt”)
Write “Script started running at ” $StartTime >> $logFile

function loop{

param(

$Object,
$AttributeName,
$Level = 0
)

# check the child attribute containing the same type of objects
$Objects = iex “`$Object.$AttributeName”

# output this item
$Object | select @{L=”Object”;E={$_}}, @{L=”Level”;E={$Level}}

# output the child items of this object
if($Objects){

# add level
$Level ++

# loop trough the same function
$Objects | %{loop -Object $_ -AttributeName $AttributeName -Level $Level}
}
}

# reset vars
$SPTaxonomies = @()

# get all taxonomy objects
$SPTaxonomies = Get-SPTaxonomySession -Site “http://sp-stage-app02:2013/” | %{

$_.TermStores | %{

$TermStore = New-Object -TypeName Psobject -Property @{

TermStore = $_.Name
Group = “”
TermSet = “”
Terms = “”
}

$_.Groups | %{

$Group = $TermStore.PSObject.Copy()
$Group.Group = $_.Name

$_.TermSets | %{

$TermSet = $Group.PSObject.Copy()
$TermSet.TermSet = $_.Name
$TermSet.Terms = ($_.Terms | %{loop -Object $_ -AttributeName “Terms” -Level 1})

$TermSet
}
}
}
}

# get maximum of levels a term has
$Levels = ($SPTaxonomies | %{$_.Terms | %{$_.Level}} | measure -Maximum).Maximum + 1

# loop throught term stores
$SPTaxonomies | %{

$SPTaxonomy = $_

# loop throught terms
$_.Terms | %{

# create a term export object
$Item = $SPTaxonomy.PSObject.Copy()
$Index = 1;while($Index -ne $Levels){
$Item | Add-Member –MemberType NoteProperty –Name “Term Level $Index” –Value $(if($_.Level -eq $Index){$_.Object.Name}else{“”})
$Index += 1
}

# output this object
$Item | Select-Object * -exclude Terms
}
} | Export-CSV -path $output -notype
}
catch [Exception]{
Write $_.Exception|format-list -force >>$logFile
Write-Host -f red $_.Exception|format-list -force
}
$EndTime = (Get-Date -UFormat “%Y-%m-%d_%I-%M-%S %p”).tostring()
Write “Script stopped at” $EndTime >> $logFile

Read How to get SharePoint features using PowerShell

Get all Users in CSV File from SharePoint Farm using PowerShell

Let us see how to get all the SharePoint users in the CSV file presented on farm using PowerShell in SharePoint 2013/2016.

This is a script that gets each SharePoint site on the farm, enumerates all the site collections and webs, and dumps them to the screen as well as a CSV file.

The current date and time are always appended to the file name so you don’t have to worry about wiping out previous results.

Get all users from SharePoint Farm using PowerShell

Below is the PowerShell Script to Get All the Users from the SharePoint farm. This PowerShell script, we can debug or test using PowerShell ISE or using Visual Studio Code.

#getalluserseverywhere
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
$timestamp = get-date -format "yyyyMMdd_hhmmtt"
$filenameStart = "AllFARMUsers"
$logfile = ("{0}{1}.csv" -f $filenamestart, $timestamp)
$header = "type,user,group,weburl,webname"
$header | out-file -FilePath $logfile
$iissitelist = get-spwebapplication
foreach($onesite in $iissitelist)
{
foreach ($SiteCollection in $onesite.sites)
{
write-host $SiteCollection -foregroundcolor Blue
foreach ($web in $SiteCollection.Allwebs)
{
write-host " " $web.url $web.name "users:" -foregroundcolor yellow
# Write-host " " $web.users | select name
foreach ($userw in $web.users)
{
#if ($userw -like "domain\*")
#{
write-host " " $userw -foregroundcolor white
#$msg = ("{0},{1} user:{2}" -f $web.url,$web.name, $userw)
$msg = ("RootUser,{0},-,{1},{2}" -f $userw, $web.url,$web.name)
$msg | out-file -FilePath $logfile -append
# }
}
foreach ($group in $web.Groups)
{
Write-host " " $web.url $group.name: -foregroundcolor green
foreach ($user in $group.users)
{
# if ($user -like "Domain\*")
#{
Write-host " " $user -foregroundcolor white
#$msg = ("{0},{1},group:{2}, user:{3}" -f $web.url, $web.name, $group, $user)
$msg = ("GroupUser,{0},{1},{2},{3}" -f $user, $group, $web.url, $web.name)
$msg | out-file -FilePath $logfile -append
#}
}
}
$web.Dispose()
}
}
}

This is how to get all the SharePoint users in CSV file format from the SharePoint farm using PowerShell.

Read How to get all SharePoint users and groups using PowerShell

How to cancel all workflows from one List in SharePoint using PowerShell

Now, let us see, how to cancel all workflows from one list in SharePoint using PowerShell. It will cancel all list workflows as well as site workflows from the SharePoint list.

We have tested this PowerShell script in our environment, Hope it will work for you.

PowerShell: Terminate a workflow for all items in a list on SharePoint

#Site URL
$web = Get-SPWeb "http://urlforsite.com";
$web.AllowUnsafeUpdates = $true;

#List Name
$list = $web.Lists["ListName"];

# Iterate through all Items in List and all Workflows on Items.
foreach ($item in $list.Items) {
foreach ($wf in $item.Workflows) {

#Cancel Workflows
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);
}
}
$web.Dispose();

Cancel all workflows from SharePoint List using PowerShell

Below is the PowerShell script to cancel all workflows from the SharePoint list using PowerShell.

$site = Get-SPSite "<your url>";
$site.AllWebs | foreach {
$web = $_;
$web.AllowUnsafeUpdates = $true;

# stop list workflows
$web.Lists | foreach {
$list = $_;
$list.Items | foreach {
$item = $_;
$item.Workflows | foreach {
$wf = $_;
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);
}
}
}

# stop site workflows

$web.Workflows | foreach {
$wf = $_;
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($wf);
}
$web.AllowUnsafeUpdates = $false;
$web.Dispose();
}

$site.Dispose();

Cancel all Suspended workflows using PowerShell in SharePoint

Let us see, how to cancel all suspended workflows using PowerShell in SharePoint 2013 or SharePoint 2016. Here, we will see how to cancel all workflows having status not equal to “Completed”.

Suppose you have a list that contains more than 1000 items and you realize the workflow which is attached to the list going to Suspended state or in progress state.

Here if you want to cancel the workflows which are not completed, then it can not be a manual task when your list is larger. If you have 10/20 items then you can do it manually, but in another case, the manual process is not a good option.

I got a very good PowerShell approach from Raymun Macaulay’s Dev Blog to cancel workflows. Thanks to the author for sharing this.

Cancel all Suspended workflows using PowerShell in SharePoint

You can run, debug and test the PowerShell script using Visual studio code or using PowerShell ISE.

Below is the PowerShell script to cancel all suspended workflows in SharePoint.

#Your Shaeproint Site URL
$web = Get-SPWeb "http://yoursharepointserver.com/yoursubsite";
$web.AllowUnsafeUpdates = $true;
#Your List Name
$list = $web.Lists["YourListName"];
$count = 0
#Loop through all Items in List then loop through all Workflows on each List Items.
foreach ($listItem in $list.Items)
{
foreach ($workflow in $listItem.Workflows)
{
#Disregard Completed Workflows
if(($listItem.Workflows | where {$_.InternalState -ne "Completed"}) -ne $null)
{
#Cancel Workflows
[Microsoft.SharePoint.Workflow.SPWorkflowManager]::CancelWorkflow($workflow);
write-output "Workflow cancelled for : " $listItem.Title;
}
}
}
$web.Dispose();

This is how to cancel all Suspended workflows using PowerShell in SharePoint 2013 or SharePoint 2016.

Read Download files from SharePoint document library using PowerShell

List out all workflows presented in SharePoint Site Collection using PowerShell

Let us see, how to list out all workflows presented in a SharePoint site collection using PowerShell.

Recently while working on a MOSS 2007 to SharePoint 2013 migration project we need to check how many workflows are there in MOSS 2007 and the corresponding attached lists also. So after a google, I found a very good script by Jeff Holliday which worked very well.

Below is the script to list out all workflows presented in a SharePoint site collection using PowerShell. First, we will see how to get all the workflows presented in MOSS 2007 site collection using PowerShell.

#Load SharePoint 2007 Assemblies
[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | out-null

$siteurl="http://SiteColURL/"
$site=new-object Microsoft.SharePoint.SPSite($siteurl)

#Initialize Workflow Count variable
$workflowcount = 0

#Foreach loop to loop through all webs, and lists with workflow associations, and exclude workflows that have previous versions and write findings to .csv file.

function Get-Workflows()
{
foreach($web in $site.AllWebs)
{
foreach($list in $web.Lists)
{
foreach($wf in $list.WorkflowAssociations)
{
if ($wf.Name -notlike "*Previous Version*")
{
$hash = @{"[URL]"=$web.Url;"[List Name]"=$list.Title;"[Workflow]"=$wf.Name}
New-Object PSObject -Property $hash | Sort-Object

}
}
}
}
}

foreach($web in $site.AllWebs)
{
foreach($list in $web.Lists)
{
foreach($wf in $list.WorkflowAssociations)
{
if ($wf.Name -notlike "*Previous Version*")
{
$workflowcount += 1
}
}
}
}

Get-Workflows | Export-csv D:\Biju\workflows.csv
"Workflow Count " + $workflowcount >> D:\Biju\workflows.csv

$site.Dispose()

[URL] [List Name] [Workflow] http://URL Tasks MyTestApp

Workflow Count 1

List all workflows from SharePoint 2013 site collection using PowerShell

The below PowerShell script is to list all workflows from SharePoint 2013/2016 site collection using PowerShell.

$site = Get-SPSite("your-site-url");
$site.AllWebs | foreach { $_.Lists | foreach { $_.WorkflowAssociations | foreach {
write-host "Site:" $_.ParentWeb.Url ", List:" $_.ParentList.Title ", Workflow:" $_.Name
} } }

Check in and Check out default page using PowerShell in SharePoint

Let us see, how to check-in and check out the default page using PowerShell in SharePoint 2013/2016/2019. Below the example, we will see how to check out and check in the SharePoint page using PowerShell.

Below is the PowerShell command which will checkout and check-in all the site’s default.aspx page and subsites under the SharePoint site collection. You can write the script in PowerShell ISE.

Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$SPsite = Get-SPSite "https://SiteURL"
foreach ($SPweb in $SPsite.AllWebs)
{
#$SPweb | Select-Object -Property Title,Url,WebTemplate
$SPFile = $SPWeb.GetFile("default.aspx");
$SPFile.CheckOut("Online",$null);
$SPFile.CheckIn(1);
$SPweb.Dispose()
}
$SPsite.Dispose()

Below is the PowerShell command which will check-in or checkout page in a particular subsite (here in this example it will check in check out the default.aspx page of Mysubsite subsite).

Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$SPsite = Get-SPSite "https://SiteURL"
foreach ($SPweb in $SPsite.AllWebs)
{
if($SPweb.Url -eq "https://SiteURL/Mysubsite")
{
#$SPweb | Select-Object -Property Title,Url,WebTemplate
$SPFile = $SPWeb.GetFile("default.aspx");
$SPFile.CheckOut("Online",$null);
$SPFile.CheckIn(1);
$SPweb.Dispose()
}
}
$SPsite.Dispose()

This is how to check-in and check out the SharePoint page using PowerShell.

Read How to export user permission in SharePoint using PowerShell

Let us see how to add links to left navigation or quick launch using PowerShell to all SharePoint sites and subsites. This PowerShell script is written by our EnjoySharePoint author JayaBharathi.

Let us explore how to add left navigation or quick launch links using PowerShell to all SharePoint sites and subsites.

Add left navigation or quick launch links using PowerShell to all SharePoint sites

In SharePoint Online, we can easily add a link in the left navigation using PowerShell. It will add in all sites and subsites under a particular SharePoint site collection.

Here we will use the CSOM PowerShell, using Windows PowerShell ISE.

add links to left navigation using powershell
add links to left navigation using powershell

Below is the PowerShell script which will add links to left navigation into the SharePoint Online sites and subsites.


#Load SharePoint CSOM Assemblies
Add-Type -Path "D:\Microsoft.SharePoint.Client.dll"
Add-Type -Path "D:\Microsoft.SharePoint.Client.Runtime.dll"

$username = "user email id"
$password = "password"
$SiteCollectionUrl="http://siteurl"

function GetClientContext($SiteCollectionUrl, $username, $password) {
     $securePassword = ConvertTo-SecureString $password -AsPlainText -Force
     $context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteCollectionUrl) 
     $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword) 
     $context.Credentials = $credentials
     return $context
}




function catchsubsites ($subsiteurl){
    $clientContext = GetClientContext $subsiteurl $username $password
    $rootWeb = $clientContext.Web
    $childWebs = $rootWeb.Webs
    $clientContext.Load($rootWeb)
    $clientContext.Load($childWebs)
    $clientContext.ExecuteQuery()
    #do something on top level site
    #write-host $rootWeb.url -ForegroundColor Yellow

	
    foreach ($childWeb in $childWebs)
    {
	

        #do something for each subsite
        write-host $childWeb.url -ForegroundColor Yellow
	#Get the Quick launch Navigation of the web
$QuickLaunch = $childWeb.Navigation.QuickLaunch
$clientContext.load($QuickLaunch)
$clientContext.ExecuteQuery()
 
#Add link to Quick Launch Navigation
$NavigationNode = New-Object Microsoft.SharePoint.Client.NavigationNodeCreationInformation
$NavigationNode.Title = "New link"
$NavigationNode.Url = "https://LINK"
#$NavigationNode.AsLastNode = $False

$clientContext.Load($QuickLaunch.Add($NavigationNode))
$clientContext.ExecuteQuery()
		
        #see if there are any subsites beneath this and loop all of them too
        catchsubsites $childWeb.url
	
    }
}

catchsubsites $SiteCollectionUrl

Once you run the above script, the link will be added to the quick launch in all the SharePoint sites and subsites under the SharePoint site collection.

Read Create HTML Reports using PowerShell

Create a document library in SharePoint using PowerShell

Let us see how to create a document library in SharePoint using PowerShell. This example explains, how to create a list or document library using PowerShell in SharePoint Online.

Below is the PowerShell script which can be used to create a list or document library in SharePoint Online.

function CreateSPOList {
    #All the pre required variable to connect SPO.
    $strSiteURL = "<< Site URL >>"
    $strUsrName = "<< Site User ID >>"
    $strLstTitle = "Loan Details"
    $strLstDesc = "Various loan details in bank!!!"
    $strLstTempID = 101
    #Reading Password from end user
    $strPWD = Read-Host "Please enter the password for $($strUsrName)" -AsSecureString
    #Creating object to SPO with the provided user name and password
    $ObjSPOCredls = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($strUsrName, $strPWD)
    # Creating client context object with the provided user name and password
    $ObjContext = New-Object Microsoft.SharePoint.Client.ClientContext($strSiteURL)
    $ObjContext.credentials = $ObjSPOCredls
    #create loan details list with the list template ID 101 (document library template)
    $ObjLstLoanDet = New-Object Microsoft.SharePoint.Client.ListCreationInformation
    $ObjLstLoanDet.title = $strLstTitle
    $ObjLstLoanDet.description = $strLstDesc
    $ObjLstLoanDet.TemplateType = $strLstTempID
    $ObjLst = $ObjContext.web.lists.add($ObjLstLoanDet)
    $ObjContext.load($ObjLst)
    # Sending request to SPO with all the pre loaded information.
    try{
        $ObjContext.executeQuery()
        write-host "Successfully Creates List $($strLstTitle)" -foregroundcolor green
    }
    catch{
        write-host "Error :: $($_.Exception.Message)" -foregroundcolor red
    }
}
CreateSPOList

To execute the PowerShell script follow the below steps: Open SharePoint Online command let as administrator and execute the script to create the SharePoint list

Once you execute the script, you can see the output for PowerShell.

Create document library sharepoint online powershell
Create document library sharepoint online powershell

After this, the document library will be created and the output will be as follows:

Create document library sharepoint online powershell
Create document library sharepoint online powershell

This is how we can create a SharePoint Online document library using PowerShell.

How to use set-spmanagedaccount to change farm account password

Let us see, how to update the farm account credentials in SharePoint 2013 using the Stsadm tool and password.

Recently I changed the system password and then I change the password in the application pool accounts, but I forget to update the farm account credentials.

So when I tried to create a web application in SharePoint, then it gave me an error like the below:

Sorry, something went wrong
The password supplied with the username Domain\Administrator was not correct. Verify that it was entered correctly and try again.
TECHNICAL DETAILS
Troubleshoot issues with Microsoft SharePoint Foundation.
Correlation ID: 1f854e9d-2303-70c8-65fd-3363d6b22fea
Date and Time: 12/25/2015 4:08:55 AM

Update Farm Account Credentials in SharePoint

We can change or update the farm account credentials in SharePoint 2013 by using STSADM.

Open your command prompt and then go to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\Bin folder

And then type the below command and enter.

stsadm -o updatefarmcredentials -userlogin EnjoySharePoint\Administrator -password [email protected]

It looks like below.

change sharepoint farm account password using PowerShell
change sharepoint farm account password using PowerShell

SharePoint 2013 change farm account password PowerShell

Now, we will see how to change the farm account password in PowerShell in SharePoint 2013.

$username="EnjoySharePoint\Administrator"
$newpassword=ConvertTo-SecureString -String "MyNewPassword" -AsPlainText -Force
Set-SPManagedAccount -Identity $username -ExistingPassword $newpassword -UseExistingPassword:$true

This is how to change the SharePoint farm account password using PowerShell.

You may like the following PowerShell SharePoint tutorials:

These PowerShell SharePoint examples explain, 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.

  • >