PowerShell SharePoint Commands And Examples

This SharePoint tutorial will discuss a few PowerShell SharePoint commands with examples. We will have SharePoint PowerShell commands related to SharePoint sites, lists, libraries, groups, etc.

If you are a SharePoint developer, then these PowerShell SharePoint commands will be helpful to you.

Table of Contents

How to use PowerShell in SharePoint

If you are new to PowerShell, then you should know how to use PowerShell in SharePoint.

  • SharePoint Online management shell: Check out this complete tutorial if you want to work with SharePoint Online using PowerShell. It will explain how to download, install, and use SharePoint Online management shell to work with SharePoint Online.
  • How to use PowerShell in SharePoint: Check out this article if you want to know how to use PowerShell in SharePoint on-premises versions like SharePoint 2019 or SharePoint 2016/2013.

Below are the PowerShell SharePoint examples, which we are going to discuss here. The commands will work in SharePoint On-premises versions like SharePoint server.

For all the PowerShell SharePoint commands, I am using Windows PowerShell ISE or Visual Studio Code to run the PowerShell commands or scripts.

PowerShell SharePoint Commands

Now, let us see various PowerShell SharePoint examples.

Create SharePoint site collection using PowerShell

We can use PowerShell to create a site collection in SharePoint on-premises versions like SharePoint 2019. Below is the PowerShell command to create a site collection in the SharePoint server. The below PowerShell script will create a team site in SharePoint.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Configuration Variables
$SiteCollURL = "http://sp-4w5yht84/sites/HR"
$SiteName = "Human Resource Team Site"
$SiteOwner = "HQAdmin\rswain"
$SiteTemplate = "STS#0"  #Team Site Template
 
#Create new Site Collection
New-SPSite -URL $SiteCollURL -OwnerAlias $SiteOwner -Template $SiteTemplate -Name $SiteName

Here is another simple example of creating a site collection in a SharePoint server.

New-SPSite is responsible for creating a new site collection in the SharePoint server.

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://SiteURL/ -name Home -owneralias SP2019\Administrator -template STS#0

If you want to create a SharePoint site on a specific content database, use the PowerShell script below.

New-SPSite -Name "Human Resource Team Site" -ContentDatabase SP2013_demo_Content -url "http://sp-4w5yht84/sites/HR" -OwnerAlias "HQAdmin\rswain" -Template "STS#1"

If you want to create a subsite under a SharePoint site collection, run the below PowerShell script. SPWeb is responsible for creating a subsite in SharePoint server 2019/2016/2013.

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

Delete a SharePoint site collection using PowerShell

Here is another SharePoint PowerShell command example. We can use PowerShell to delete a SharePoint site collection using PowerShell. Below is the PowerShell script to delete a site collection in SharePoint.

Remove-SPSite -Identity "http://sp-4w5yht84/sites/HR" 

The above SharePoint PowerShell script will delete the HR site.

Sometimes, you might not be able to delete a SharePoint site collection from the browser or SharePoint central administration. In those cases, you can use the PowerShell command to forcefully delete a site collection in SharePoint.

Below is the PowerShell script.

$Site = Get-SPSite http://sp-4w5yht84/sites/HR
$SiteContentDB = $site.ContentDatabase
$SiteContentDB.ForceDeleteSite($Site.Id, $false, $false)

You can run the PowerShell script below if you want to delete all the site collections from a SharePoint web application.

$WebAppURL="http://sp-4w5yht84/sites/HR"
Get-SPWebApplication $WebAppURL | Get-SPSite -Limit ALL | Remove-SPSite -Confirm:$false

Using PowerShell, we can also delete all the sites from a SharePoint site collection. You can execute the below PowerShell script.

Get-SPSite "http://sp-4w5yht84/sites/HR" -Limit ALL | Remove-SPSite -Confirm:$false

Get all site collections in a SharePoint farm using PowerShell

If you want to get all the site collections from your SharePoint farm using PowerShell, you can use the below PowerShell command.

Get-SPWebApplication | Get-SPSite -Limit All | Format-Table -Property URL,ContentDatabase

If you want to get all the SharePoint site collections created in the last 30 days using PowerShell, run the below PowerShell command.

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}

If you want to get all the SharePoint site collections created today, run the below PowerShell script.

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

If you want to get the SharePoint site collection created date using PowerShell, run the below PowerShell command.

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

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

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 it in csv or text format, then you can write the following:

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

This is how to get all the site collections from a content database using PowerShell.

Get all subsites from SharePoint Site Collection using PowerShell

There might be some requirements for getting all subsites from a SharePoint site collection using PowerShell. After executing the command, all the subsites will be exported to an Excel file.

Get-SPWebApplication http://sp-4w5yht84/sites/HR | Get-SPSite -Limit All | Get-SPWeb -Limit All | Select Title, URL | 
Export-CSV C:\SharePoint_Sites_Report.csv -NoTypeInformation

Update SharePoint Site Collection details using PowerShell

If you need to update a SharePoint site collection title, description, or language using PowerShell, then you can use the below PowerShell script.

function Using-Culture (
   [System.Globalization.CultureInfo]   $culture = (throw "USAGE: Using-Culture -Culture culture -Script {…}"),
   [ScriptBlock] $script = (throw "USAGE: Using-Culture -Culture culture -Script {…}"))
   {
     $OldCulture = [Threading.Thread]::CurrentThread.CurrentCulture
     $OldUICulture = [Threading.Thread]::CurrentThread.CurrentUICulture
         try {
                 [Threading.Thread]::CurrentThread.CurrentCulture = $culture
                 [Threading.Thread]::CurrentThread.CurrentUICulture = $culture
                 Invoke-Command $script
         }
         finally {
                 [Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
                 [Threading.Thread]::CurrentThread.CurrentUICulture = $OldUICulture
         }
}

$web = Get-SPWeb "http://sp-4w5yht84/sites/HR"
$newTitle = "My new Title"
$newDesc = "My new Description"

# de-DE = German - Germany ; en-US = English - United States
Using-Culture de-DE { $web.Title=$newTitle; $web.Description=$newDesc; $web.Update() }

The above command will update the SharePoint server site collection details.

Change SharePoint Site URL using PowerShell

It is easy to change a SharePoint server site collection URL using PowerShell. The below PowerShell SharePoint example is about how to change a SharePoint site or site collection URL using PowerShell.

$site = Get-SPSite http://sp-4w5yht84/sites/HR
$site.Rename("http://sp-4w5yht84/sites/HumanResource")

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 be changed.

Change a SharePoint Site logo using PowerShell

Now, we will see how to change the SharePoint site logo using PowerShell. SharePoint server site default logo comes from the _layouts/images/ folder.

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

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 = "SharePoint site Logo"
$web.Update()

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

Backup and Restore content database using PowerShell in SharePoint

Sometimes, you need to back up and restore a content database using PowerShell in SharePoint. Below is the PowerShell command to back up a content database using PowerShell in SharePoint.

Backup-SPFarm -Directory <BackupFolder> -BackupMethod {Full | Differential} -Item <ContentDatabaseName> [-Verbose]

If you want to restore a content database in SharePoint server 2019, SharePoint 2016/2013, run the below PowerShell script.

Get-SPContentDatabase -ConnectAsUnattachedDatabase  -DatabaseName <DatabaseName> -DatabaseServer <DatabaseServer>

Backup and Restore the SharePoint Site using PowerShell

We can also use the PowerShell script to backup and restore a SharePoint site using PowerShell.

First, let us see how to back up a SharePoint server site using PowerShell.

Backup-SPSite http://SiteURL/sites/HR -Path C:\Backup\site_name.bak -UseSqlSnapshot

If you want to restore a SharePoint site collection using PowerShell, run the below PowerShell command.

Restore-SPSite http://SiteURL/sites/HR -Path C:\Backup\site_name.bak -Force -DatabaseServer SQLBE1 -DatabaseName SQLDB1

You can use the above command in SharePoint Server 2019, SharePoint Server subscription, SharePoint 2016, etc.

Create a List in SharePoint using PowerShell

Let us check a few more PowerShell SharePoint commands and examples related to SharePoint lists and libraries.

To create a SharePoint list using PowerShell, run the following PowerShell script.

Add-PSSnapin 'Microsoft.SharePoint.PowerShell' -ErrorAction SilentlyContinue            
$SPweb = Get-SPWeb -Identity 'http://SiteURL/sites/HR'            
$ListTemplate = $SPweb.ListTemplates['Custom List']            
$SPweb.Lists.Add('SharePoint', 'List creation demo using PowerShell' , $ListTemplate)

The above PowerShell script will create a custom SharePoint list.

Delete a SharePoint list using PowerShell

We can easily delete a list from a SharePoint server site using Microsoft PowerShell. Below is the PowerShell command to delete a SharePoint list.

Add-PSSnapin 'Microsoft.SharePoint.PowerShell' -ErrorAction SilentlyContinue            
$SPweb = Get-SPWeb -Identity 'http://SiteURL/sites/HR'            
$list = $SPweb.Lists['Employees List']
$list.Delete()

You can run the PowerShell command below to prevent the deleting option in a SharePoint list.

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

Once you execute the above PowerShell command, users cannot delete the above SharePoint list.

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, 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()

Get all lists and libraries from a SharePoint Site using PowerShell

Here is another PowerShell SharePoint command example. Let us see how to get all lists and libraries from a SharePoint site using PowerShell.

Below is the PowerShell command to get all the lists from a SharePoint site collection.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  
$Site = Get-SPSite "http://SiteURL/sites/HR"
# get the all sub sites of site
$SubSites = $Site.AllWebs
$SubSites | ForEach-Object { 
$Site = $_
# get all lists from site
$lists = $Site.Lists | Where-Object { $_.BaseType -eq 'GenericList' }
$lists | ForEach-Object {                 
    New-Object -TypeName PSObject -Property @{
              ListName = $_.Title
              SiteName = $Site.Title
              SiteUrl = $Site.Url
}}}

This will give all the custom lists from the above SharePoint site collection.

The below command will get all the libraries from a SharePoint site collection. It will get all the document libraries from the SharePoint site collection.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
$Site = Get-SPSite "http://SiteURL/sites/HR"
# get the all sub sites of site
$SubSites = $Site.AllWebs
$SubSites | ForEach-Object { 
$Site = $_
# get all document Libraries from site
$lists = $Site.Lists | Where-Object { $_.BaseType -eq 'DocumentLibrary' }
$lists | ForEach-Object {                                     
    New-Object -TypeName PSObject -Property @{
              LibraryName = $_.Title
              SiteName = $Site.Title
              SiteUrl = $Site.Url
}}}

If you want to get all the lists and libraries whose versioning is enabled in SharePoint using PowerShell, then check the below PowerShell script.

Get-SPWeb http://SiteURL/sites/HR |
   Select -ExpandProperty Lists |
   Where { -not $_.hidden -and
           $_.EnableVersioning -eq $true} |
   Select ParentWebUrl, title

Add item to SharePoint list using PowerShell

Let us check a few more PowerShell SharePoint commands.

If you want to know how to add an item to a SharePoint list using PowerShell.

Add-PSSnapin 'Microsoft.SharePoint.PowerShell' -ErrorAction SilentlyContinue
$SPweb = Get-SPWeb -Identity 'http://SiteURL/sites/HR'
$list = $SPweb.Lists['Employees Details']
$item = $list.Items.Add()
$item['Title'] = 'Alex'
$item.update()

Once you execute the above SharePoint PowerShell scripts, it will add an item to the SharePoint list.

Let us see how to insert bulk items into a SharePoint Online list using PowerShell.

Here, I have a “Laptop” list 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 "MyPassword@123" -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.

Insert multiple or bulk items to SharePoint Online list using PowerShell

The above code will add a single item to the SharePoint Online list. But you can also add multiple items to the SharePoint Online list using PowerShell CSOM.

Below is the PowerShell script.

Add-Type -Path 'E:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll'
Add-Type -Path 'E:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'
$SiteURL = "https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"
$ListName="Logging"
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$securePassword=ConvertTo-SecureString "*******" -AsPlainText -Force
$Context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials("******@onlysharepoint2013.onmicrosoft.com", $securePassword)
$Web = $Context.Web
$List = $web.get_lists().getByTitle($ListName)
for ($i=1; $i -le 10; $i++)
{
$itemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$listItem = $list.addItem($itemCreateInfo)
$listItem["Title"] = "Item-$($i)"
$listItem["Description"] = "Description-$($i)"
$listItem.Update()
$Context.ExecuteQuery()
}

The above PowerShell script will add 10 items to the SharePoint Online list.

Insert multiple or bulk items to SharePoint Online list using PowerShell
PowerShell add multiple or bulk items to SharePoint Online list

Delete item from a SharePoint list using PowerShell

Run the below PowerShell command if you want to delete an item from a SharePoint list using PowerShell.

System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)

$site = new-object Microsoft.SharePoint.SPSite("http://SiteURL/sites/HR")
$relweburl = ”/Test”
$web = $site.openweb($relweburl)

$list = $web.Lists[“Employees List”]

$listItems = $list.Items
$listItemsTotal = $listItems.Count

for ($item=$listItemsTotal-1;$item -ge 0; $item–)
{

Write-Host(“DELETED: ” )
$listItems[$item].Delete()
}
}

Once you run the above PowerShell command, it will delete all the items from the SharePoint list.

If you want to delete bulk items from a SharePoint list using PowerShell, run the below PowerShell command.

Add-PSSnapin Microsoft.SharePoint.Powershell -ea SilentlyContinue
$web = get-spweb "http://SiteURL/sites/HR"
$list = $web.lists["List Title"]
$query = New-Object Microsoft.SharePoint.SPQuery
$query.ViewAttributes = "Scope='Recursive'"
$query.RowLimit = 1000
$query.ViewFields = "<FieldRef Name='ID'/>"
$query.ViewFieldsOnly = $true
do
{
   $listItems = $list.GetItems($query)
   $query.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
   foreach($item in $listItems)
   {
     Write-Host "Deleting Item - $($item.Id)"
     $list.GetItemById($item.Id).delete()
   }
}
while ($query.ListItemCollectionPosition -ne $null) 

Using the above PowerShell command, you can delete items in bulk from a SharePoint list using PowerShell.

Copy items from one list to another list using PowerShell in SharePoint

Here is another PowerShell for SharePoint command example. Here, you will get to know how to copy items from one SharePoint list to another SharePoint list using PowerShell.

$WebURL = "http://SiteURL/sites/HR"
$SourceListName = "Source SharePoint List"
$TargetListName= "Destination SharePoint List"
 
#Get Objects
$web = Get-SPWeb $WebURL
$SourceList = $web.Lists[$SourceListName]
$TargetList = $web.Lists[$TargetListName]
 
#Get all source items
$SourceColumns = $sourceList.Fields
$SourceItems = $SourceList.GetItems();
 
#Iterate through each item and add to target list
Foreach($SourceItem in $SourceItems)
{
    $TargetItem = $TargetList.AddItem()
    Foreach($column in $SourceColumns)
    {
        if($column.ReadOnlyField -eq $False -and $column.InternalName -ne "Attachments")
        {
             $TargetItem[$($column.InternalName)] = $sourceItem[$($column.InternalName)];
        }
    }
   $TargetItem.Update();
}

There might be scenarios where you want to copy data from one column to another column in a SharePoint list using PowerShell.

Below is the PowerShell script to copy data from one column to another in 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()

Delete bulk items from a SharePoint list using PowerShell

Are you looking for a PowerShell script to delete multiple items from a SharePoint server list using PowerShell? Using PowerShell, here is the script to delete bulk items from a SharePoint list.

Add-PSSnapin Microsoft.SharePoint.Powershell -ea SilentlyContinue
$web = get-spweb "http://SiteURL/sites/HR"
$list = $web.lists["List Title"]
$query = New-Object Microsoft.SharePoint.SPQuery
$query.ViewAttributes = "Scope='Recursive'"
$query.RowLimit = 1000
$query.ViewFields = "<FieldRef Name='ID'/>"
$query.ViewFieldsOnly = $true
do
{
   $listItems = $list.GetItems($query)
   $query.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
   foreach($item in $listItems)
   {
     Write-Host "Deleting Item - $($item.Id)"
     $list.GetItemById($item.Id).delete()
   }
}
while ($query.ListItemCollectionPosition -ne $null) 

Enable or Disable list throttling in SharePoint PowerShell

Microsoft has set a default threshold limit of 5000 items to the SharePoint list; once your list increases beyond, you will get a message like The number of items in this list exceeds the list view threshold.

There are many cases where you want to deal with a huge amount of data in the SharePoint list, whereas you need to bypass the threshold limit of a particular SharePoint list. So, to override the default throttling settings. Just execute the PowerShell below to add list items exceeding the threshold limits.

The straightforward solution to overcome the threshold issue is to increase the threshold limit for the particular SharePoint list.

Below is the PowerShell command to disable the list throttling for a particular SharePoint server list.

Add-PSSnapin Microsoft.SharePoint.PowerShell
$web = Get-SPWeb http://SiteURL/
$web.AllowUnsafeUpdates = $True
$list = $web.Lists[“YourListName”]
$list.EnableThrottling = $false
$list.Update()
$web.AllowUnsafeUpdates = $False
$web.Update()
$web.Dispose()

Once the threshold limit is disabled, users can able to insert items into the SharePoint list.

In the same way, by using PowerShell, we can enable the list threshold limit for a SharePoint Online list.

Below is the PowerShell command enabling list throttling for a particular SharePoint list. It will work for a list in SharePoint server subscription edition, SharePoint server 2019 or even in SharePoint server 2016/2013.

Add-PSSnapin Microsoft.SharePoint.PowerShell
$web = Get-SPWeb http://SiteURL/
$web.AllowUnsafeUpdates = $True
$list = $web.Lists[“YourListName”]
$list.EnableThrottling = $true
$list.Update()
$web.AllowUnsafeUpdates = $False
$web.Update()
$web.Dispose()

This is how to enable or disable list throttling in the SharePoint server.

Create a document library in SharePoint using PowerShell

It is very easy to create a document library in SharePoint Online using PowerShell. Here is a complete PowerShell script to create a document library in SharePoint Online site using PowerShell.

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

Create a folder in a document library in SharePoint using PowerShell

Below is the PowerShell SharePoint command to create a folder under a document library in the SharePoint server.

$webUrl = "http://SiteURL/"
$listName = "My Parent List"
$numberFoldersToCreate = 4000;
$folderNamePrefix = "folder";
 
# Open web and library
$web = Get-SPWeb $webUrl
$list = $web.Lists[$listName]
 
# Create desired number of subfolders
for($i=1; $i -le $numberFoldersToCreate; $i++)
{
$folder = $list.AddItem("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, "$folderNamePrefix$i")
$folder.Update()
write-host $i
}
 
#Dispose web
$web.Dispose()

This is how to create folders in a SharePoint document library using PowerShell.

Upload multiple documents to a SharePoint document library using PowerShell

We can also use PowerShell to upload multiple documents to a SharePoint document library. The below PowerShell script will upload documents from a local folder to a SharePoint document library. Here, I have created a folder locally and added a few files inside it.

function UploadDocuments($destination, $File)
{
$securePassword=ConvertTo-SecureString "Qwe@12345" -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential("MYSP\Administrator",$securePassword)
$webclient=New-Object System.Net.WebClient
$webclient.Credentials=$credentials
$webclient.UploadFile($destination+"/"+$File.Name,"PUT",$File.FullName)
}
$destination="http://mypc:29024/sites/HydTraining/Shared%20Documents/"
$fileDirectory="E:\Users\Administrator\Desktop\FilesToUpload\*.*"
foreach($fileName in Get-ChildItem $fileDirectory)
{
UploadDocuments -destination $destination -File $fileName
Write-Output "Upload file " $fileName
}
Write-Host "Documents uploaded successfully"

Once you run the script, you will see files will be uploaded to the document library like below:

Upload multiple documents to a SharePoint document library using PowerShell

Activate or Deactivate features using PowerShell in SharePoint

Features are very important in SharePoint on-premises. Let us see how to activate or deactivate features using PowerShell in SharePoint.

We can provide the feature name and then activate the feature using PowerShell in SharePoint. Here is the PowerShell command to activate the SharePoint feature.

Enable-SPFeature –Identity Reporting –url http://SiteURL/

The above command will activate the reporting feature in a SharePoint site.

In the same way, we can also use PowerShell to deactivate a feature. Below is the PowerShell command to deactivate features using PowerShell in SharePoint.

Disable-SPFeature –Identity Reporting –url http://SiteURL/

There are a lot of features that are hidden by default in a SharePoint on-premises site. But, we can use PowerShell to activate those hidden features in SharePoint. Here are the steps you can follow.

First, get all the features to get the Name or GUID of the feature 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 the PowerShell command below:

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

Get all SharePoint features using PowerShell

If you want to get all the features of a SharePoint 2019 site, you can run the below PowerShell command.

Get-SPFeature –Site http://SiteURL/

If you want to get the feature details based on the feature id in SharePoint using PowerShell, then run the below PowerShell script.

Add-PSSnapin "Microsoft.SharePoint.PowerShell"
Get-SPFeature -Limit ALL | Where-Object {$_.id -eq "22a9ef51-737b-4ff2-9346-694633fe4416"}
sharepoint powershell commands

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

Create a SharePoint group using PowerShell

Now, let us check out a few PowerShell SharePoint examples related to SharePoint groups.

Do you have any requirements to create a SharePoint group using PowerShell? Below is the PowerShell script to create a SharePoint group using PowerShell.

Add-PSSnapin Microsoft.SharePoint.PowerShell –ErrorAction SilentlyContinue
 
#Custom Function to Create new SharePoint Group
function Create-SPGroup
{ 
    param ($SiteURL, $GroupName, $PermissionLevel, $GroupDescription) 
 
    try
    {
        #Get the Web
        $web = Get-SPWeb -Identity $SiteURL
         
        if($web -ne $null)
        {
            #Check if Group Exists already
            if ($web.SiteGroups[$GroupName] -ne $null) 
            { 
                write-Host "Group $GroupName exists Already!" -ForegroundColor Red
            } 
            else 
            { 
                #Create SharePoint Group
                $Web.SiteGroups.Add($GroupName, $web.Site.Owner, $web.Site.Owner, $GroupDescription) 
                #Get the newly created group and assign permission to it
                $Group = $web.SiteGroups[$groupName] 
                $roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($group) 
                $roleDefinition = $web.Site.RootWeb.RoleDefinitions[$permissionLevel] 
                $roleAssignment.RoleDefinitionBindings.Add($roleDefinition) 
                $web.RoleAssignments.Add($roleAssignment) 
                $web.Update() 
 
                write-Host "Group: $GroupName created successfully!" -ForegroundColor Green
            } 
  
            $web.Dispose()
        }
    }
    catch [System.Exception]
    {
        write-host $_.Exception.ToString() -ForegroundColor Red
    }
}
 
#Call the function to create Sharepoint group
Create-SPGroup "http://SiteURL/" "My Powershell Group"

The above PowerShell script will work in SharePoint server 2019, SharePoint 2016/2013, etc.

Delete a SharePoint group using PowerShell

You can also use PowerShell to delete a group in SharePoint. Below is the PowerShell SharePoint command to delete a SharePoint group using PowerShell in the SharePoint server subscription edition, SharePoint server 2019/2016/2019, etc.

Add-PSSnapin “Microsoft.SharePoint.PowerShell”
#Get web
$spWeb = Get-SPWeb "http://SiteURL/";
#Your group name
$GroupName="My SharePoint Group"

if($spWeb.SiteGroups[$GroupName] -ne $null)
{
$spWeb.SiteGroups.Remove($GroupName)
$spWeb.Update()
Write-Host “Group Deleted!”
}
else
{
Write-Host “Group doesn’t Exists!”
}

Once you run the above PowerShell script, it will delete the “My SharePoint Group” group from the SharePoint site.

Add or remove a user from a SharePoint group using PowerShell

Let us see how to add or remove a user from a SharePoint group using Microsoft PowerShell.

Below is the PowerShell SharePoint command to add users to a SharePoint group.

#Get the Web
$web=Get-SPWeb "http://SiteURL/"
#Get the SharePoint Group
$Group= $web.Groups["DHLOwners"]
$userName = "SPADmin\rswain"
 
#Add User to the site collection
$user = $web.EnsureUser($UserName)
 
#Add User to the Group
$group.AddUser($user)

Below is the PowerShell SharePoint Command to remove users from the SharePoint group.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
Function RemoveUser-FromGroup($SiteURL, $GroupName, $UserAccount)
{
 try
    {
     $ErrorActionPreference = "Stop"
   
     #Get the Web
     $web=Get-SPWeb $SiteURL
     
     #Get the User to Remove
     $User  = Get-SPUser -Identity $UserAccount -Web $web
 
     #Get the Group by its name
     $Group = $Web.sitegroups | Where-Object {$_.Name -eq $GroupName}
     if($Group -ne $null)
     {
         #sharepoint powershell delete user from group
         $Group.RemoveUser($User)
         Write-Host "$($User) Removed from the Group: $($GroupName)"
     }
   }
 catch
    {
           #Write error message on screen and to a LOG file
           write-host $_.Exception.Message
    }
 finally
    {
           $ErrorActionPreference = "Continue"
    }
}
 
#Call the function to remove user from SharePoint group
RemoveUser-FromGroup "http://SiteURL/" "DHL Owners" "SPADMIN\rswain"

This is how to add or remove users from a SharePoint group using PowerShell.

There might be requirements where you want to remove a user from all the SharePoint groups on the SharePoint site. Below is the PowerShell SharePoint command to remove a user from all the SharePoint groups.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
Function RemoveUser-FromAllGroups($SiteURL, $UserAccount)
{
     #Get the Web
     $web=Get-SPWeb $SiteURL
     
     #Get the User to Remove
     $User  = $Web.EnsureUser($UserAccount)
 
     #Iterate through all Groups
     foreach($Group in $Web.Groups)
     {
         $GroupUser = $Group.Users | where {$_.UserLogin -eq $User.UserLogin}
         #Check if user member of the group
         if($GroupUser -ne $null)
         {
            #remove user from sharepoint group using powershell
            $Group.RemoveUser($User)
            Write-Host "$($User) Removed from the Group: $($Group)"
         }
     }
 }
 
 #Call the function to remove a user from all groups in the site 
 RemoveUser-FromAllGroups "http://SiteURL/" "SPADMIN\rswain"

The above code will work in SharePoint server subscription edition and SharePoint server 2019/2016/2013, etc.

Get all users from a SharePoint group using PowerShell

Below is the PowerShell SharePoint command to get all users from the SharePoint group using PowerShell in SharePoint 2019 or SharePoint 2016/2013.

function GetSPAllSPUsers($SiteCollectionURL,$SPListName) 
{ 
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") > $null 
    $site = new-object Microsoft.SharePoint.SPSite($SiteCollectionURL)     
    $web = $site.openweb() 
    $list = $web.Lists[$SPListName] 
    $siteCollUsers = $web.SiteUsers 
     
    foreach($user in $siteCollUsers) 
        { 
            Write-Host " ------------------------------------- " 
            Write-Host "Site Collection URL:", $SiteCollectionURL 
            if($list.DoesUserHavePermissions([Microsoft.SharePoint.SPBasePermissions]::ViewListItems,$user) -eq $true) 
                { 
                    Write-Host "User : ", $user.LoginName 
                    Write-Host "Assigned Permissions : ", $list.GetUserEffectivePermissions($user.LoginName) 
                }             
            Write-Host " ------------------------------------- "         
        } 
     
        $web.Dispose() 
        $site.Dispose() 
 } 

Once you run the above PowerShell script, it will get all the users from a SharePoint group.

Change Master Page and Page Layout using PowerShell in SharePoint

If you are using classic SharePoint, you might be required to change the master page and page layout.

By using PowerShell, we can easily change the master page in the SharePoint server. Below is the PowerShell command to change the master page of a SharePoint site.

The below PowerShell command you can use to set a custom master page to a SharePoint site.

$web = Get-SPWeb http://win-pfcp2dgt8di/sites/EnjoySharePoint
$web.CustomMasterUrl = “/_catalogs/masterpage/mycustom.master”
$web.MasterUrl = “/_catalogs/masterpage/mycustom.master”
$web.Update()

This is how to set the master page in SharePoint using PowerShell. The script will work in the SharePoint server subscription edition as well as in the SharePoint server 2019 or SharePoint server 2016/2013.

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

Below is the PowerShell script to change the page layout of default.aspx page in a SharePoint 2013/2016/2019 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()

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 is how to change the page layout in SharePoint using PowerShell.

Collect ULS logs for specific CorrelationID in SharePoint using PowerShell

Now, we will discuss how to 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

The above PowerShell script will work in all the SharePoint on-premise versions.

Attach event receivers to a SharePoint list using PowerShell

In this example, we will see how to attach an event receiver to a SharePoint list using PowerShell.

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

The PowerShell script will attach an event receiver to a SharePoint list using PowerShell.

Conclusion

I hope you got an idea of how to use PowerShell in SharePoint on-premises versions like SharePoint Server 2019, SharePoint 2016, or SharePoint 2013. And I hope you got the SharePoint Powershell commands examples.

  • Create SharePoint site collection using PowerShell
  • Delete a SharePoint site collection using PowerShell
  • Get all site collections in a SharePoint farm using PowerShell
  • Get all subsites from SharePoint Site Collection using PowerShell
  • Update SharePoint Site Collection details using PowerShell
  • Change SharePoint Site URL using PowerShell
  • Change a SharePoint Site logo using PowerShell
  • Backup and Restore content database using PowerShell in SharePoint
  • Backup and Restore the SharePoint Site using PowerShell
  • Create a List in SharePoint using PowerShell
  • Delete a SharePoint list using PowerShell
  • Change SharePoint list Settings using PowerShell
  • Get all lists and libraries from a SharePoint Site using PowerShell
  • Add item to SharePoint list using PowerShell
  • Delete item from a SharePoint list using PowerShell
  • Copy items from one list to another list using PowerShell in SharePoint
  • Delete bulk items from a SharePoint list using PowerShell
  • Enable or Disable list throttling in SharePoint PowerShell
  • Create a document library in SharePoint using PowerShell
  • Create a folder in a document library in SharePoint using PowerShell
  • Activate or Deactivate features using PowerShell in SharePoint
  • Get all SharePoint features using PowerShell
  • Create a SharePoint group using PowerShell
  • Delete a SharePoint group using PowerShell
  • Add or remove a user from a SharePoint group using PowerShell
  • Get all users from a SharePoint group using PowerShell
  • Change Master Page and Page Layout using PowerShell in SharePoint
  • Collect ULS logs for specific CorrelationID in SharePoint using PowerShell
  • Attach event receivers to a SharePoint list using PowerShell

You may also like the following tutorials:

  • Thank you for the article and information!

    I’ve often wondered, from only the client-side, for SP2016 on-prem, is it possible to use PowerShell commands as a Site Collections admin without having access to the SharePoint Servers? That is, remote capability to use PowerShell?

  • Great list! Do you happen to have something similar to retrieve a list of all 3rd party applications that are installed on each site? [not whats in the app library]

  • >