PowerShell SharePoint Commands And Examples

If you are a SharePoint developer, then you should have some expertise in PowerShell. Here, I will demonstrate some PowerShell examples related to SharePoint sites, lists, libraries, groups, etc. This tutorial covers PowerShell SharePoint commands and examples.

The commands will work in SharePoint On-premises versions like SharePoint Server. For all PowerShell SharePoint commands, I use either Windows PowerShell ISE or Visual Studio Code to run the PowerShell commands or scripts.

Table of Contents

PowerShell SharePoint Commands

Here are the PowerShell SharePoint examples that I have gathered while working with SharePoint on-premises versions for years.

Create a SharePoint Site Collection using PowerShell

We can use PowerShell to create a site collection in SharePoint on-premises versions. 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

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

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 example of a SharePoint PowerShell command. 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 delete a site collection in SharePoint forcefully.

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 to delete all 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 following 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 following 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}

To retrieve the creation date of a SharePoint site collection using PowerShell, run the following PowerShell command.

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

In this example, we will demonstrate how to programmatically retrieve all site collections associated with a specific content database using PowerShell in SharePoint Server.

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:

Get All Site Collections in a SharePoint Farm using PowerShell

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

Get All Subsites from the SharePoint Site Collection using PowerShell

There may be requirements for retrieving 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 following PowerShell SharePoint example demonstrates 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 executing the PowerShell script, the site title and description will be updated.

Change a SharePoint Site Logo using PowerShell

Now, we will see how to change the SharePoint site logo using PowerShell. The SharePoint server site’s default logo is located in the _layouts/images/ folder.

If you want to use your new logo, you can place it 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 the SharePoint Content Database using PowerShell

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, run the following 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 following PowerShell command.

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

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 will be unable to delete the specified SharePoint list.

Change SharePoint List Settings using PowerShell

We will see now how to change SharePoint list settings using PowerShell. Through PowerShell, you can modify the SharePoint list title, description, and enable or disable versioning, among other settings.

#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

Let’s see how to retrieve 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 retrieve all custom lists from the SharePoint site collection mentioned above.

The command below retrieves all 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 retrieve all lists and libraries with enabled versioning in SharePoint using PowerShell, then refer to the PowerShell script below.

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

Add an Item to the SharePoint List using PowerShell

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, an item will be added 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 a 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

Delete an Item from a SharePoint List using PowerShell

Run the PowerShell command below 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 following 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 command example for SharePoint. 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. Simply execute the PowerShell script below to add list items that exceed 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 will be able to insert items into the SharePoint list.

Similarly, using PowerShell, we can enable the list threshold limit for a SharePoint Online list.

Below is the PowerShell command that enables list throttling for a specific SharePoint list. It will work for a list in SharePoint on-premises versions.

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

Creating a document library in SharePoint Online using PowerShell is very easy. Here is a complete PowerShell script to create a document library in a 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 command to create a folder within a document library on 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 that 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 following 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 Server site, you can run the following 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 on-premises versions

Delete a SharePoint group using PowerShell

You can also use PowerShell to delete a SharePoint group. Below is the PowerShell SharePoint command to delete a SharePoint group using PowerShell in the SharePoint Server.

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 may be requirements where you need to remove a user from all SharePoint groups on a 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 both SharePoint Server subscription edition and SharePoint on-premises versions.

Get All Users from a SharePoint Group using PowerShell

Below is the PowerShell command to retrieve all users from a SharePoint group using PowerShell.

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.

Collect ULS logs for a Specific CorrelationID in SharePoint using PowerShell

Now, we will discuss how to collect ULS logs for a specific CorrelationID using PowerShell. Below is the PowerShell command to collect ULS logs for a 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.

Hide SharePoint Document Library using PowerShell

Here is the PowerShell script to hide a SharePoint document library from a site contents page. This will work on the SharePoint on-premises versions.

$siteUrl = "https://tsinfo.sharepoint.com/sites/TSInfoClassic/"
$listName="MyTestList"
$web = Get-SPWeb $siteUrl
$list = $web.Lists[$listName]
$list.Hidden = $showHideValue
$list.Update()

Get Current SharePoint User Details using PowerShell

We can retrieve the current logged-in user details using PowerShell in SharePoint. We can run the below PowerShell script using Windows PowerShell ISE or by using Visual Studio Code.

Here is the complete PowerShell script.

Add-PSSnapin Microsoft.Sharepoint.Powershell
$site=Get-SPSite "http://win-eqalhem27jl:7575/sites/one/"
$web=$site.RootWeb
$strLoginName=$web.CurrentUser.LoginName
$strID=$web.CurrentUser.ID
$strName=$web.CurrentUser.Name
Write-Host " Current User Id : " $strID -ForegroundColor green;
Write-Host " Current User Login Name : " $strLoginName -ForegroundColor green;
Write-Host " Current User Name : " $strName -ForegroundColor green

Output:

sharepoint get current user id powershell

Conclusion

I hope you got an idea of how to use PowerShell in SharePoint on-premises versions. And I hope you got the SharePoint Powershell commands examples.

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]

  • >

    Live Webinar: Build an IT Help Desk App using Power Apps and Power Automate

    Join this free live session and learn how to build a fully functional IT Help Desk application using Power Apps and Power Automate—step by step.

    📅 29th Apr 2026 – 10:00 AM EST | 7:30 PM IST

    Build a High-Performance Project Management Site in SharePoint Online

    User registration Power Apps canvas app

    DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

    Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App

    Power Platform Tutorial FREE PDF Download

    FREE Power Platform Tutorial PDF

    Download 135 Pages FREE PDF on Microsoft Power Platform Tutorial. Learn Now…