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
$web.WebTemplate
$web.WebTemplateId

 


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)

Backup-SiteCollections

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.

http://sp2010adminpack.codeplex.com/wikipage?title=Backup-SiteCollections&referringTitle=Documentation


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]
}
$rootWeb.Dispose()

#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]
$assignment.RoleDefinitionBindings.Add($role)
$_.RoleAssignments.Add($assignment)

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.”
$site.Dispose()
}

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…

http://get-spscripts.com/2011/02/add-sharepoint-or-ad-groupuser-to-all.html


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…

cls

# 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 = @{

                    “URL”=$web.Site.MakeFullUrl(“$($web.ServerRelativeUrl.TrimEnd(‘/’))/$($item.Url)”);

                    “CheckedOutBy”=$item.CheckedOutBy;

                    “CheckedOutByEmail”=$item.CheckedOutByEmail

                }

                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 = @{

                        “URL”=$web.Site.MakeFullUrl(“$($web.ServerRelativeUrl.TrimEnd(‘/’))/$($item.Url)”);

                        “CheckedOutBy”=$item.File.CheckedOutByUser;

                        “CheckedOutByEmail”=$item.File.CheckedOutByUser.Email

                    }

                    New-Object PSObject -Property $hash

                }

            }

        }

        $web.Dispose()

    }

}

Get-CheckedOutFiles | Out-GridView

From here –> http://blog.falchionconsulting.com/index.php/2011/06/getting-and-taking-ownership-of-checked-out-files-using-windows-powershell/


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

ForEach

    {

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

          $($_.CheckedOutBy)”

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

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

     }

     $spWeb.Dispose()

}

Here’s an example on running the function:

CheckInDocument http://SP

Found here