PowerShell SharePoint Commands

PowerShell SharePoint Commands
SharePoint deveopment training course

Learn some PowerShell SharePoint Command in this tutorial. In any organization, they are mostly using PowerShell command for all operation in SharePoint. Here I have explained few commands which are mainly required for all SharePoint developer.

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

Below are the PowerShell examples which we are going to discuss here. The commands will work in SharePoint On-premises versions like SharePoint 2019/2016/2013/2010.

SharePoint 2016 Tutorial Contents

  1. Create Site collection
  2. Create site collection in specific content database
  3. Site delete
  4. Force delete SharePoint site collection with PowerShell
  5. Delete all site collections under a web application
  6. Bulk delete site collections with PowerShell
  7. Getting site information
  8. All site collection the farm
  9. Getting all sub sites
  10. Get all subsites of a subsite using PowerShell
  11. Backup Content DB
  12. Restore Content DB
  13. Backup Site
  14. Restore site
  15. Get all lists
  16. Get all libraries
  17. Create a List
  18. Delete List
  19. Adding a item to a list
  20. Finding list and library by any properties
  21. Delete item in a list
  22. Bulk Delete SharePoint Items in a Large List
  23. Activate features
  24. Deactivate features
  25. Get all features
  26. Add user to a SharePoint group
  27. Remove user from SharePoint group
  28. Remove user from all SharePoint groups
  29. Create a SharePoint group
  30. Delete a group
  31. Get all users
  32. Get all groups
  33. Change site collection URL
  34. Change site collection Title and description
  35. Copy list data from one list to another
  36. Create a folder under a library

The below screenshot is the Powershell window where we will execute our code. Also, you can use Windows PowerShell ISE or Visual Studio Code to run the PowerShell commands or scripts.

PowerShell SharePoint Commands
PowerShell SharePoint Commands

Create site collection using PowerShell in SharePoint

Below is the PowerShell SharePoint command or script to create a site collection using PowerShell in SharePoint. You may also like below SharePoint site collection tutorials:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Configuration Variables
$SiteCollURL = "https://www.enjoysharepoint.com/sites/RajDemo"
$SiteName = "Welcome To Enjo SharePoint"
$SiteOwner = "HQAdmin\rswain"
$SiteTemplate = "STS#0"  #Team Site Template
 
#Create new Site Collection
New-SPSite -URL $SiteCollURL -OwnerAlias $SiteOwner -Template $SiteTemplate -Name $SiteName

PowerShell create a site collection in a specific content database in SharePoint

Below is the PowerShell command to create site collection in specific content database in SharePoint. You may like following SharePoint content database tutorials:

New-SPSite -Name "Welcome To Enjo SharePoint" -ContentDatabase SP2013_demo_Content -url https://www.enjoysharepoint.com/sites/RajDemo `-OwnerAlias "HQAdmin\rswain" -Template "STS#1"

Delete site collection PowerShell

Below is the PowerShell SharePoint Command to delete site collection PowerShell in SharePoint. You may like different ways to delete site in SharePoint:

Remove-SPSite -Identity "https://www.enjoysharepoint.com/sites/RajDemo" 

Force delete SharePoint site collection using PowerShell

Below is the PowerShell SharePoint Command to force delete SharePoint site collection using PowerShell script.

$Site = Get-SPSite https://www.enjoysharepoint.com/sites/RajDem
$SiteContentDB = $site.ContentDatabase
$SiteContentDB.ForceDeleteSite($Site.Id, $false, $false)

PowerShell delete all site collections in a web application in SharePoint

Below is the PowerShell SharePoint command which will delete all site collections in a web application in SharePoint 2013/2016/2019.

$WebAppURL="https://www.enjoysharepoint.com/sites/RajDemo"
Get-SPWebApplication $WebAppURL | Get-SPSite -Limit ALL | Remove-SPSite -Confirm:$false

Bulk delete site collections with PowerShell

Below the PowerShell script which will delete site collections in bulk in SharePoint.

Get-SPSite "https://www.enjoysharepoint.com/sites/RajDemo" -Limit ALL | Remove-SPSite -Confirm:$false

PowerShell Get site information in SharePoint

Below is the PowerShell SharePoint command to get site information in SharePoint 2013/2016.

Get-SPSite 'https://www.enjoysharepoint.com/sites/RajDemo' | Get-SPWeb -Limit All | Select Title

PowerShell get all site collections in a SharePoint farm

Below is the PowerShell SharePoint command, which will retrieve all site collections in a SharePoint farm.

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

Get all subsites from Site Collection using PowerShell

Below is the PowerShell script to retrieve all subsites from SharePoint Site collection using PowerShell.

Get-SPWebApplication https://www.enjoysharepoint.com/sites/RajDemo | Get-SPSite -Limit All | Get-SPWeb -Limit All | Select Title, URL | 
Export-CSV C:\SharePoint_Sites_Report.csv -NoTypeInformation

Get all subsites of a subsite using PowerShell in SharePoint

Below is the PowerShell SharePoint commands to get all subsites of a subsite using PowerShell in SharePoint 2013/2016/2019.

param ( [Parameter(Mandatory=$true)][ValidateNotNullOrEmpty()] [String]$StartWeb, [Boolean]$IncludeStartWeb = $true )
 
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
$subsites = ((Get-SPWeb $StartWeb).Site).allwebs | ?{$_.url -like "$StartWeb*"}
 
foreach($subsite in $subsites) { Write-Host $subsite.url }

SharePoint PowerShell backup content database

Below is the PowerShell command to take backup of content database in SharePoint.

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

SharePoint PowerShell restore a content database

Below is the PowerShell SharePoint command which will restore SharePoint content database in SharePoint 2013/2016.

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

Backup site using PowerShell SharePoint 2013/2016

Below is the PowerShell command to backup site in SharePoint 2013.

Backup-SPSite https://www.enjoysharepoint.com/sites/RajDemo -Path C:\Backup\site_name.bak -UseSqlSnapshot

Restore site using PowerShell in SharePoint 2013/2016

Below is the PowerShell command to restore site in SharePoint 2013/2016 using PowerShell.

Restore-SPSite https://www.enjoysharepoint.com/sites/RajDemo -Path C:\Backup\site_name.bak -Force -DatabaseServer SQLBE1 -DatabaseName SQLDB1

Get all lists in a SharePoint Site using Powershell

Below is the PowerShell SharePoint commands to get all lists in a SharePoint site using PowerShell.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  
$Site = Get-SPSite "https://www.enjoysharepoint.com/sites/RajDemo"
# 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
}}}

Get all libraries in a SharePoint Site using Powershell

Below is the PowerShell script which will retrieve all libraries in a SharePoint site.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
$Site = Get-SPSite "https://www.enjoysharepoint.com/sites/RajDemo"
# 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
}}}

Create a List using PowerShell in SharePoint

Below is the PowerShell script to create a list in SharePoint 2010/2013/2016 using PowerShell. Different ways to create list in SharePoint:

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

Delete List in SharePoint using PowerShell

Below is the PowerShell command to delete list in SharePoint 2013/2016/2019.

Add-PSSnapin 'Microsoft.SharePoint.PowerShell' -ErrorAction SilentlyContinue            
$SPweb = Get-SPWeb -Identity 'https://www.enjoysharepoint.com/sites/RajDemo'            
$list = $SPweb.Lists['SharePoint']            
$item1 = $list.Items            
$item1[0].Delete()

PowerShell add item to SharePoint list

Below is the PowerShell command to add item to SharePoint 2013/2016 list.

Add-PSSnapin 'Microsoft.SharePoint.PowerShell' -ErrorAction SilentlyContinue            
$SPweb = Get-SPWeb -Identity 'https://www.enjoysharepoint.com/sites/RajDemo'            
$list = $SPweb.Lists['SharePoint']            
$item1 = $list.Items.Add()            
$item1['Title'] = 'Chendrayan'            
$item1.update()

Retrieve list and libraries having versioning enabled in SharePoint using PowerShell

Below is the PowerShell script which will retrieve list and libraries having versioning enabled and the list is not hidden in SharePoint using PowerShell.

Get-SPWeb https://www.enjoysharepoint.com/sites/RajDemo |
   Select -ExpandProperty Lists |
   Where { -not $_.hidden -and
           $_.EnableVersioning -eq $true} |
   Select ParentWebUrl, title

Delete Item in a specific list in SharePoint using PowerShell

Below is the PowerShell SharePoint command to delete items from a SharePoint list.

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

$site = new-object Microsoft.SharePoint.SPSite("https://www.enjoysharepoint.com/sites/RajDemo")
$relweburl = ”/rajtest”
$web = $site.openweb($relweburl)

$list = $web.Lists[“RajList”]

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

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

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

SharePoint PowerShell bulk delete list items

Add-PSSnapin Microsoft.SharePoint.Powershell -ea SilentlyContinue
$web = get-spweb "https://www.enjoysharepoint.com/sites/RajDemo"
$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) 

Activate features using PowerShell in SharePoint

Below is the PowerShell command to activate feature in SharePoint. You may like following SharePoint features tutorials:

Enable-SPFeature –Identity Reporting –url https://www.enjoysharepoint.com/sites/RajDemo

Deactivate features using PowerShell in SharePoint

Below is the PowerShell command to deactivate features using PowerShell in SharePoint.

Disable-SPFeature –Identity Reporting –url https://www.enjoysharepoint.com/sites/RajDemo

Get all features using PowerShell in SharePoint

Below is the PowerShell command to get all the features in SharePoint 2013/2016.

Get-SPFeature –Site https://www.enjoysharepoint.com/sites/RajDemo

Add user to a SharePoint group using PowerShell

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

#Get the Web
$web=Get-SPWeb "https://www.enjoysharepoint.com/sites/RajDemo"
#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)

Remove user from SharePoint group using PowerShell

Below is the PowerShell SharePoint Command to remove users from 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 "https://www.enjoysharepoint.com/sites/RajDemo" "DHL Owners" "SPADMIN\rswain"

Remove user from all SharePoint groups using PowerShell

Below is the PowerShell command to remove users from all SharePoint groups using PowerShell in SharePoint 2013/2016.

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 "https://www.enjoysharepoint.com/sites/RajDemo" "SPADMIN\rswain"

Create a SharePoint group using PowerShell

Below is the PowerShell command or script to create a SharePoint group using PowerShell in SharePoint 2013/2016.

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 "https://www.enjoysharepoint.com/sites/RajDemo" "My Powershell Group"

Delete a SharePoint group using PowerShell

Below is the PowerShell SharePoint command to delete a SharePoint group using PowerShell in SharePoint 2013/2016. You may like following SharePoint group tutorials:

Add-PSSnapin “Microsoft.SharePoint.PowerShell”
#Get web
$spWeb = Get-SPWeb "https://www.enjoysharepoint.com/sites/RajDem";
#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!”
}

Get all SharePoint users using PowerShell in SharePoint 2013/2016

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

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

Get all groups in SharePoint using PowerShell

Below is the PowerShell command to get all groups in SharePoint using PowerShell.

$web = Get-SPWeb $webUrl;
$groups = $web.AssociatedGroups;

Change Site collection URL using PowerShell in SharePoint

Below is the PowerShell SharePoint command to change the site collection URL in SharePoint 2013/2016 using PowerShell. Also, read 3 Different ways to Change Site Collection URL in SharePoint 2013/2016 using PowerShell.

$site = Get-SPSite https://www.enjoysharepoint.com/sites/RajDem
$site.Rename("https://www.enjoysharepoint.com/sites/RajDemo1")

Change site collection Title and Description using PowerShell SharePoint 2013/2016

Below is the PowerShell SharePoint command to change the SharePoint site collection title and description.

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 "https://www.enjoysharepoint.com/sites/RajDem"
$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() }

SharePoint PowerShell copy list items to another list

The below PowerShell command is to copy list items to another list using PowerShell in SharePoint 2013/2016.

$WebURL = "https://www.enjoysharepoint.com/sites/RajDem"
$SourceListName = "Source SharePoint"
$TargetListName= "Destination SharePoint"
 
#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();
}

Create a folder under a library in SharePoint using PowerShell

Below is the PowerShell SharePoint command to create a folder under a library in SharePoint 2013/2016. Below are also different ways to create a folder in SharePoint:

$webUrl = "https://www.enjoysharepoint.com/sites/RajDem"
$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()

These are some PowerShell SharePoint command to work site, list, library, groups, etc. in SharePoint and I will come up with more command in my next article.

Check out Best Alternative to InfoPath -> Try Now

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

About Rajkiran Swain

Rajkiran is currently working as a SharePoint Consultant in QATAR . Rajkiran having 6 + years of experience in Microsoft Technologies such as SharePoint 2019/2016/2013/2010, MOSS 2007,WSS 3.0, Migration, Asp.Net, C#.Net, Sql Server, Ajax, jQuery etc.He is C#Corner MVP (2 Times).

View all posts by Rajkiran Swain →
  • 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?