Most Useful SharePoint PowerShell Commands

SharePoint Server is a web-based collaborative platform that integrates with Microsoft Office. To configure SharePoint site settings, system administrators often use the SharePoint Management Shell that is installed with the SharePoint product. Running the SharePoint Management Shell calls the Windows PowerShell runtime environment and executes a script file named sharepoint.ps1, which loads the Windows PowerShell snap-in for SharePoint and runs a few commands. These commands are not very important; they include choosing C:\Users\Username as the home location for command execution and running the latest version of PowerShell console.

A better option is to use the PowerShell ISE. Not only does it include many cmdlets created especially for managing SharePoint, it also offers color-highlighted code, a debug engine and a cmdlet search engine.

To load the SharePoint snap-in, we need to run the following command:

Add-PSSnapin Microsoft.SharePoint.PowerShell

After that, it is prudent to update PowerShell help in order get the latest information about the Microsoft SharePoint PowerShell cmdlets:

Update-Help

So, what cmdlets are available in the SharePoint snap-in? Here is the command that will list all of them for you:

Get-Command -Module "Microsoft.SharePoint.PowerShell"

Now let’s take a closer look at the most useful SharePoint cmdlets.

Getting SharePoint Site Information

Get-SPSite cmdlet is the main cmdlet for getting information about your SharePoint site collections. It lists the URLs of your SharePoint sites and their compatibility levels (SharePoint versions).

Getting SharePoint Site Information Using Get-SPSite cmdlet

Using the Select-Object parameter with this cmdlet, we can get specific properties about a site, such as the site owner, storage usage, maximum quota level and last content modified date:

Get-SPSite "http://sharepoint/sites/ent" | Select-Object url, owner, @{Expression={$_.Usage.Storage}}, @{Expression={$_.Audit.AuditFlags}}, readonly, LastContentModifiedDate, @{Express={$_.QuotaStorageMaximumLevel}}

Getting SharePoint Site Information Using the Select-Object

In addition, we can export information about all sites in our SharePoint farm to a csv file:

Get-SPWebApplication http://sharepoint/ | Get-SPSite -Limit All | Get-SPWeb -Limit All | Select Title, URL, ID, ParentWebID | Export-CSV C:\root\sharepointinventory.csv -NoTypeInformation

We can also use the Get-SPSite cmdlet to create a SharePoint PowerShell script that lists all the groups and their members for a particular SharePoint site:

$site = Get-SPSite http://sharepoint/sites/ent/

$groups = $site.RootWeb.sitegroups

foreach ($grp in $groups) {"Group: " + $grp.name; foreach ($user in $grp.users) {"  User: " + $user.name} }

$site.Dispose()

Getting a Lists of Groups and Their Members for a Particular SharePoint Site

If you need a complete permissions report for a SharePoint site, run the following code, specifying the SharePoint site URL ($SPSiteURL) and the path to export the data to a csv file ($ExportFile) :

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$SPSiteUrl = "http://sharepoint/sites/ent"
$SPSite = New-Object Microsoft.SharePoint.SPSite($SPSiteUrl);
$ExportFile = "C:\root\Permissions.csv"

"Web Title,Web URL,List Title,User or Group,Role,Inherited" | out-file $ExportFile

foreach ($WebPath in $SPSite.AllWebs)
{
   if ($WebPath.HasUniqueRoleAssignments)
        {
          $SPRoles = $WebPath.RoleAssignments;
          foreach ($SPRole in $SPRoles)
          {
            foreach ($SPRoleDefinition in $SPRole.RoleDefinitionBindings)
            {
                $WebPath.Title + "," + $WebPath.Url + "," + "N/A" + "," + $SPRole.Member.Name + "," + $SPRoleDefinition.Name + "," + $WebPath.HasUniqueRoleAssignments | out-file $ExportFile -append
            }
          }
        }
        
        foreach ($List in $WebPath.Lists)
        {
           if ($List.HasUniqueRoleAssignments)
           {
             $SPRoles = $List.RoleAssignments;
             foreach ($SPRole in $SPRoles)
             {
               foreach ($SPRoleDefinition in $SPRole.RoleDefinitionBindings)
               {
                    $WebPath.Title + "," + $WebPath.Url + "," + $List.Title + "," + $SPRole.Member.Name + "," + $SPRoleDefinition.Name | out-file $ExportFile -append
               }
             }
           }
        }
}
$SPSite.Dispose();

To find a certain file on a SharePoint site, we need to use the Get-SPWeb cmdlet. Here is a script that searches for a file whose name contains the word “readme” in the “http://sharepoint/sites/ent” site:

Get-SPWeb http://sharepoint/sites/ent |
   Select -ExpandProperty Lists |
   Where { $_.GetType().Name -eq "SPDocumentLibrary" -and
           -not $_.Hidden } |
   Select -ExpandProperty Items |
   Where { $_.Name -like "*readme*" } |
   Select Name, {$_.File.Length}, url

Now let’s make a report that will output all files created by a certain user. This script can be helpful, for example, when an employee leaves the company and you need to transfer their data to other people.

Get-SPWeb http://sharepoint/sites/ent |
   Select -ExpandProperty Lists |
   Where { $_.GetType().Name -eq "SPDocumentLibrary" -and
          -not $_.Hidden } |
   Select -ExpandProperty Items |
   Where { $_["Created By"] -like "*system*" } |
   Select Name, url, {$_["Created By"]}

Our last script using the Get-SPWeb cmdlet reports on all files with a specified extension:

Get-SPWeb http://sharepoint/sites/ent |
Select -ExpandProperty Lists |
   Where { $_.GetType().Name -eq "SPDocumentLibrary" -and
           -not $_.Hidden } |
   Select -ExpandProperty Items |
   Where { $_.Name -Like "*.rtf" } |
   Select Name,
         @{Name="URL";
          Expression={$_.ParentList.ParentWeb.Url + "/" + $_.Url}}

Using PowerShell to Manage SharePoint Sites and Objects

New SharePoint sites are typically created using a template. To get a list of all site templates, run the Get-SPWebTemplate cmdlet with no parameters.

We use the Get-SPWebTemplate cmdlet with the New-SPSite cmdlet to create a new SharePoint site based on a template. Here is an example of a script for creating a site using the “Team Site” template (STS#0):

$template = Get-SPWebTemplate "STS#0"
New-SPSite -Url "http://sharepoint/sites/netwrixteamsite" -OwnerAlias "enterprise\t.simpson" -Template $template

To delete a site, we use the Remove-SPSite cmdlet:

Remove-SPSite -Identity "http://sharepoint/sites/netwrixteamsite" -GradualDelete

Sometimes, you might need to change the site collection administrator. Execute the following script to add admin rights to the specified user:

Set-SPSite -Identity "http://sharepoint/sites/netwrixteamsite" -SecondaryOwnerAlias " i:0#.w|enterprise\i.scur"

Now, let’s see how to manage permissions to our site collections. First, let’s add certain access rights to a particular Active Directory user account. In this case, the user “enterprise\t.simpson” will be given “Contributor” rights to the site “http://sharepoint/sites/ent”. Note that before a regular user account name like “enterprise\t.simpson”, you need to use the prefix “i:0#.w|”. Otherwise, the execution will fail and the script will generate an error.

Set-SPUser -Identity "i:0#.w|enterprise\t.simpson" -Web http://sharepoint/sites/ent -AddPermissionLevel "Contributor"

To add permissions to a certain AD security group, use the same script but type the name of the group instead of the name of the user account.

To add a user to a group, use this command:

Set-SPUser -Identity "i:0#.w|enterprise\j.carter" -Web http://sharepoint/sites/ent -Group "Enterprise Owners"

Conclusion

As you can see, managing and reporting on SharePoint sites using SharePoint PowerShell scripts is not as hard as it may seem at first. In fact, in some cases, it is much faster to run a script rather than generate a report from the admin audit log.

To keep your Microsoft SharePoint environment secure and highly available, you also need to carefully track changes there. Netwrix Auditor for SharePoint can easily generate reports on SharePoint changes, giving you complete visibility into who changed what, when and on which SharePoint farm. You can also receive notifications about critical changes automatically. In addition, Netwrix Auditor for SharePoint will give you full information about current permissions and how they were granted, as well as show any broken inheritance in your SharePoint environment.