Category Archives: PowerShell

SharePoint 2013 Online – How to setup PowerShell access

You’re going to quickly find out that you need access to run PowerShell commands against your online environment. This blog summarizes how to set it up.



SharePoint 2010 – Find out which site template was used to create a site

via powershell…

$web = get-spweb http://MyURL


Easy Site Collection Backups

If you need a simple cost effective way to schedule backups your site collections, here’s the script for the job. Just add a scheduled task and your set. (how to add scheduled task)


This script was designed to be scheduled and forgotten. This loops through all of your web applications and site collections and backs up each one individually. Each backup is prefixed with the current date and time. Old backups (3 days or older by default) are deleted. A log file is created to track the backup process.

Add a SharePoint or AD group/user to all sites in a site collection using PowerShell

This is a great script that allows you to do batch permission updates…

function AddAccountToAllSites ($siteURL, $accountName, $permLevel, [switch]$skipRootSite, $newGroupDescription)
#Get Site Collection
$site = Get-SPSite $siteURL

#Check if the accountName variable contains a slash – if so, it is an AD account
#If not, it is a SharePoint Group
$rootWeb = $site.RootWeb
if ($accountName.Contains(“\”)) { $account = $rootWeb.EnsureUser($accountName) }
else {
#If the SharePoint Group does not exist, create it with the name and description specified
if (!$rootWeb.SiteGroups[$accountName])
$rootWeb.SiteGroups.Add($accountName, $rootWeb.CurrentUser, $rootWeb.CurrentUser, $newGroupDescription)
$account = $rootWeb.SiteGroups[$accountName]

#Step through each site in the site collection
$site | Get-SPWeb -limit all | ForEach-Object {

#Check if the user has chosen to skip the root site – if so, do not change permissions on it
if (($skipRootSite) -and ($site.Url -eq $_.Url)) { write-host “Root site” $_.Url “will be bypassed” }
else {
#Check if the current site is inheriting permissions from its parent
#If not, set permissions on current site
if ($_.HasUniqueRoleAssignments) {

$assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($account)
$role = $_.RoleDefinitions[$permLevel]

write-host “Account” $accountName “added to site” $_.Url “with” $permLevel “permissions.”
else {
write-host “Site” $_.Url “will not be modified as it inherits permissions from a parent site.”
#Display completion message and dispose of site object
write-host “Operation Complete.”

Once the script has been run, you can use it to assign permissions to your site collection by calling the function. Here are some scenarios:

Add the Active Directory user PACDOMAIN\Phil to all sites except the root site and assign Read permissions to them:

  • AddAccountToAllSites -siteURL “http://portal” -accountName “PACDOMAIN\Phil” -permLevel “Read” -skipRootSite

Add the Active Directory user PACDOMAIN\Phil to all sites including the root site and assign Read permissions to them:

  • AddAccountToAllSites -siteURL “http://portal” -accountName “PACDOMAIN\Phil” -permLevel “Read”

Add the Active Directory group PACDOMAIN\Portal Users to all sites including the root site and assign Read permissions to it:

  • AddAccountToAllSites -siteURL “http://portal” -accountName “PACDOMAIN\Portal Users” -permLevel “Read”

Add the SharePoint group “Test Group” to all sites except the root site and assign Full Control permissions to it. I am also assuming that this group has already been created in the site collection:

  • AddAccountToAllSites -siteURL “http://portal” -accountName “Test Group” -permLevel “Full Control” -skipRootSite

Add the SharePoint group “Test New Group” to all sites except the root site and assign Contribute permissions to it. This time I would like to create the group in the site collection as it doesn’t currently exist, and so I am also specifying the group description to be used during creation:

  • AddAccountToAllSites -siteURL “http://portal” -accountName “Test New Group” -permLevel “Contribute” -skipRootSite -newGroupDescription “This is a test group”

I found the script here…

Powershell to find out web parts are on your pages

Here’s a script to get a list of what web parts are on each page in a site collection. Helps when you need to find all the pages you need to update with a new version of a web part…


# Add SharePoint cmdlets reference

Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

function enumerateWebParts($Url) {

    $site = new-object Microsoft.SharePoint.SPSite $Url

    foreach($web in $site.AllWebs) {

        if ([Microsoft.SharePoint.Publishing.PublishingWeb]::IsPublishingWeb($web)) {

            $pWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)

            $pages = $pWeb.PagesList


            Write-Host “Processing Web:” $pWeb.Url “…” -ForegroundColor Magenta


            foreach ($item in $pages.Items) {

                $fileUrl = $webUrl + “/” + $item.File.Url

                Write-Host ”   ” $fileUrl -ForegroundColor Green

                $manager = $item.file.GetLimitedWebPartManager([System.Web.UI.WebControls.Webparts.PersonalizationScope]::Shared);

                $wps = $manager.webparts

                $wps | select-object @{Expression={$pWeb.Url};Label=”Web URL”},@{Expression={$fileUrl};Label=”Page URL”}, DisplayTitle, IsVisible, @{Expression={$_.GetType().ToString()};Label=”Type”}



        else {

            Write-Host ”   Not a publishing web:” $web.Url”. Looking for Site Pages library.” -ForegroundColor Magenta

            $pages = $null

            $pages = $web.Lists[“Site Pages”]


            if ($pages) {

                Write-Host ”   ” $pages.Title “found.” -ForegroundColor Green


                foreach ($item in $pages.Items) {

                    $fileUrl = $webUrl + “/” + $item.File.Url

                    $manager = $item.file.GetLimitedWebPartManager([System.Web.UI.WebControls.Webparts.PersonalizationScope]::Shared);

                    $wps = $manager.webparts

                    $wps | select-object @{Expression={$pWeb.Url};Label=”Web URL”},@{Expression={$fileUrl};Label=”Page URL”}, DisplayTitle, IsVisible, @{Expression={$_.GetType().ToString()};Label=”Type”}



            else {

                Write-Host ”    Site Pages library not found.” -ForegroundColor Red




        Write-Host “… completed processing” $web “…” -ForegroundColor Magenta




$row = enumerateWebParts(‘http://yoursitecollection’)

$row | Out-GridView

Find all checked out files in the farm

Here’s a better script I found to get all checked out files on the farm. You can just add the check-in code from my previous blog if needed.

function Get-CheckedOutFiles() {

    foreach ($web in (Get-SPSite -Limit All | Get-SPWeb -Limit All)) {

        Write-Host “Processing Web: $($web.Url)…”

        foreach ($list in ($web.Lists | ? {$_ -is [Microsoft.SharePoint.SPDocumentLibrary]})) {

            Write-Host “`tProcessing List: $($list.RootFolder.ServerRelativeUrl)…”

            foreach ($item in $list.CheckedOutFiles) {

                if (!$item.Url.EndsWith(“.aspx”)) { continue }

                $hash = @{





                New-Object PSObject -Property $hash


            foreach ($item in $list.Items) {

                if ($item.File.CheckOutStatus -ne “None”) {

                    if (($list.CheckedOutFiles | where {$_.ListItemId -eq $item.ID}) -ne $null) { continue }

                    $hash = @{





                    New-Object PSObject -Property $hash







Get-CheckedOutFiles | Out-GridView

From here –>

Check in documents with Powershell SharePoint 2010

This will help out when you need to force files to be checked in. It can also be modified to find all the checked out files and notify users…

function CheckInDocument([string]$url)


$spWeb = Get-SPWeb $url

$getFolder = $spWeb.GetFolder(“Shared Documents”)

$getFolder.Files | Where { $_.CheckOutStatus -ne “None” } |



          Write-Host “$($_.Name) is Checked out To:


          $_.CheckIn(“Checked In By Administrator”)

          Write-Host “$($_.Name) Checked In” -ForeGroundColor Green




Here’s an example on running the function:

CheckInDocument http://SP

Found here

Powershell through all your sites

This script specifically gets site collection admins, but it can be modified to get other data you might be interested in…

$rootSite = New-Object Microsoft.SharePoint.SPSite($siteUrl)
$spWebApp = $rootSite.WebApplication
foreach($site in $spWebApp.Sites)
    foreach($siteAdmin in $site.RootWeb.SiteAdministrators)
        Write-Host "$($siteAdmin.ParentWeb.Url) - $($siteAdmin.DisplayName)"
found it here..

Reset Managed Account Password

At first I was worried this was going to be a pain, but it’s one powershell command. You will be prompted to enter the new password and that’s it.

Set-SPManagedAccount -Identity YourDomain\YourUserName -UseExistingPassword


Stop being Strict with my PDF!

Have you had the issue where even after you change the “Browser File Handling” setting in Central Admin from “Strict” to “Permissive” the “Save As” prompt still displays when you try to open PDF files? You’re going to need PowerShell to fix it, but at least a fix exists. I found a response to a blog post with the script below.

The complete blog is here with

What a life saver…

copy the following text into notepad and save as script.PS1

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
$siteURL = $args[0]
$site = Get-SPSite($siteURL)

foreach ($web in $site.AllWebs) {
Write-Host “Inspecting ” $web.Title
foreach ($list in $web.Lists) {
if($list.browserfilehandling -eq “Strict”) {
Write-Host “Changing ” $list.Title
$list.browserfilehandling = “Permissive”;

Then, on your sharepoint server, place the script somewhere easy, namely your c: directory – navigate to said directory in powershell then type the following: