Archive

Posts Tagged ‘SharePoint’

Managing Quota Templates on SharePoint through PowerShell

August 10, 2013 3 comments

Quota templates are a seldom used but practically important feature in SharePoint. Important because it allows administrators to keep tabs on what sites can consume what level of storage without having to keep close watch on them. Defining a quota template with a high water mark (for warning when its reached) and a maximum level is the first step to this. Depending upon use, an administrator may have to define a large number of quota templates but doing this through the UI in SharePoint Central Administration is tedious.

clip_image001

One of these forms needs to be filled out for each template and it could get tiresome if there are tens of templates to create or edit. The easier way to do this? PowerShell.

The files in the archive posted here are PowerShell scripts that will allow an administrator to get a quick view of all available quota templates in XML and then allow the same XML file to accrue additions, modifications and changes pertaining to deletions that can be applied back to the set.

The following need to be ensured before running the scripts

  1. Run the scripts locally using the SharePoint Management Shell on a computer where SharePoint Server 2013 is installed and configured.
  2. Run the scripts as a farm administrator with permissions to alter quota templates. If the user is able to use the Central Administration UI to manage quota templates, then the user will be able to run these scripts.
  3. If there are permission issues with executing the script, ensure Add-SPShellAdmin is run for the user running the script.
  4. Use Set-ExecutionPolicy to temporarily tone the restrictions down if the shell complains about the script not being signed.

GetQuotaTemplates.ps1

##########################################
# Script:   GetQuotaTemplates.ps1
# Function: Retrieves all quota templates
#           defined on the farm in XML
# Author:   Lenny Ankireddi (2013)
##########################################

function Get-SPQuotaTemplates
{
    # Prepare XML structure
    $xmlText =
@"
<?xml version="1.0" encoding="UTF-8" ?>
<QuotaTemplates AsOn="">
    <QuotaTemplate Name="Sample" Action="None|Add|Edit|Delete" StorageMaxLevelInMB="0" StorageWarnLevelInMB="0" UserCodeMaxLevel="0" UserCodeWarnLevel="0" />
</QuotaTemplates>
"@

    # Read the XML string into an object
    $xmlDoc = [xml]$xmlText

    # Read the sample element
    $sampleQuotaTemplate = @($xmlDoc.QuotaTemplates.QuotaTemplate)[0]

    # Get a reference to the content web service
    $service = [Microsoft.SharePoint.Administration.SPWebService]::ContentService

    # Iterate through the list of quota templates
    $service.QuotaTemplates | ForEach-Object {
        # Clone the sample element
        $newQuotaTemplate = $sampleQuotaTemplate.Clone()

        # Set the attributes of the element with the quota template properties
        $newQuotaTemplate.Name = $_.Name
        $newQuotaTemplate.Action = "None"
        $newQuotaTemplate.StorageMaxLevelInMB = [string]($_.StorageMaximumLevel / 1024 / 1024)
        $newQuotaTemplate.StorageWarnLevelInMB = [string]($_.StorageWarningLevel / 1024 / 1024)
        $newQuotaTemplate.UserCodeMaxLevel = [string]$_.UserCodeMaximumLevel
        $newQuotaTemplate.UserCodeWarnLevel = [string]$_.UserCodeWarningLevel

        # Add the element to the QuotaTemplates node as a new child
        $xmlDoc.QuotaTemplates.AppendChild($newQuotaTemplate)
    }

    # Remove Sample node
    $sample = $xmlDoc.QuotaTemplates.QuotaTemplate | Where-Object { $_.Name -eq "Sample" }
    $xmlDoc.QuotaTemplates.RemoveChild($sample)

    # Set date and time when generated
    $now = Get-Date
    $xmlDoc.QuotaTemplates.AsOn = [string]$now

    # Save the XML as a file to the current location
    $currentLocation = Get-Location
    $xmlDoc.Save("$currentLocation\QuotaTemplates.xml")

    # Report completion
    Write-Host -f Green "The quota template information has been saved to QuotaTemplates.xml."
}

Get-SPQuotaTemplates

This script fetches the quota templates currently specified on the local SharePoint farm and their related properties and places these details in an XML file in the same location as the script file.

clip_image002

The XML file will be named QuotaTemplates.xml and will be of the following format.

<?xml version="1.0" encoding="UTF-8"?>
<QuotaTemplates AsOn="04/24/2013 14:58:32">
    <QuotaTemplate Name="Personal Site" Action="None" StorageMaxLevelInMB="100" StorageWarnLevelInMB="80" UserCodeMaxLevel="300" UserCodeWarnLevel="200" />
    <QuotaTemplate Name="Sample 01" Action="None" StorageMaxLevelInMB="4096" StorageWarnLevelInMB="2048" UserCodeMaxLevel="0" UserCodeWarnLevel="0" />
    <QuotaTemplate Name="Sample 02" Action="None" StorageMaxLevelInMB="5120" StorageWarnLevelInMB="4096" UserCodeMaxLevel="0" UserCodeWarnLevel="0" />
</QuotaTemplates>

This file will serve as in input descriptor for the other script that manages the creation, edition and deletion of quota templates. Running the GetQuotaTemplates.ps1 script will overwrite any existing QuotaTemplates.xml file in the script file location. A file with the same name is expected as input by the ManageQuotaTemplates.ps1 script. Therefore if an input file is required for posterity, a copy of the file will need to be saved away manually.

ManageQuotaTemplates.ps1

###############################################
# Script:   ManageQuotaTemplates.ps1
# Function: Applies changes to quota templates
#           based on definition in XML
# Author:   Lenny Ankireddi (2013)
###############################################

function ManageQuotaTemplates
{
    # Get a reference to the content service
    $service = [Microsoft.SharePoint.Administration.SPWebService]::ContentService

    # Read XML input file
    $currentLocation = Get-Location
    $xmlDoc = New-Object XML
    $xmlDoc.Load("$currentLocation\QuotaTemplates.xml");
    $xmlDoc.QuotaTemplates.QuotaTemplate | Foreach-Object {

        $Name = $_.Name
        $StorageMaxLevel = $_.StorageMaxLevelInMB
        $StorageWarnLevel = $_.StorageWarnLevelInMB
        $UserCodeMaxLevel = $_.UserCodeMaxLevelInMB
        $UserCodeWarnLevel = $_.UserCodeWarnLevelInMB

        switch ($_.Action)
        {
            "Add"
            {
                Write-Host "Attempting to add new quota template $name..."
                # Check if quota template already exists
                if ($service.QuotaTemplates[$Name] -ne $null)
                {
                    Write-Host -f Red "Quota Template $Name already exists. Cannot add a new one with the same name. Use the Edit action to alter the existing template."
                    Write-Host ""
                }
                else
                {
                    # Get a reference to a quota template object
                    Write-Host "    Getting a reference to a new quota template object..."
                    $quotaTemplate = New-Object Microsoft.SharePoint.Administration.SPQuotaTemplate

                    # Set mandatory properties on the quota template
                    Write-Host "    Setting quota template properties..."
                    $quotaTemplate.Name = $Name
                    $quotaTemplate.StorageMaximumLevel = [int]$StorageMaxLevel * 1024 * 1024
                    $quotaTemplate.StorageWarningLevel = [int]$StorageWarnLevel * 1024 * 1024
                    $quotaTemplate.UserCodeMaximumLevel = [double]$UserCodeMaxLevel
                    $quotaTemplate.UserCodeWarningLevel = [double]$UserCodeWarnLevel

                    # Add the new quota template to the list of quota templates
                    Write-Host "    Adding the quota template $Name..."
                    $service.QuotaTemplates.Add($quotaTemplate)

                    # Update the service
                    $service.Update()

                    Write-Host -f Green "Quota Template $Name has been added."
                    Write-Host ""
                }
            }

            "Edit"
            {
                Write-Host "Attempting to edit quota template $name..."
                # Check if quota template already exists
                if ($service.QuotaTemplates[$Name] -ne $null)
                {
                    # If found, edit the template with new property values
                    Write-Host "    Quota template was located; editing it..."
                    $service.QuotaTemplates[$Name].Name = $Name
                    $service.QuotaTemplates[$Name].StorageMaximumLevel = [int]$StorageMaxLevel * 1024 * 1024
                    $service.QuotaTemplates[$Name].StorageWarningLevel = [int]$StorageWarnLevel * 1024 * 1024
                    $service.QuotaTemplates[$Name].UserCodeMaximumLevel = [double]$UserCodeMaxLevel
                    $service.QuotaTemplates[$Name].UserCodeWarningLevel = [double]$UserCodeWarnLevel

                    # Update the service
                    $service.Update()

                    Write-Host -f Green "Quota Template $Name has been edited."
                    Write-Host ""
                }
                else
                {
                    Write-Host -f Red "Quota Template $Name was not found. Verify that it exists and name has been correctly typed in XML input. Use the Add action to add a new template by this name."
                    Write-Host ""
                }
            }

            "Delete"
            {
                Write-Host "Attempting to delete quota template $name..."
                # Check if quota template can be found
                if ($service.QuotaTemplates[$Name] -ne $null)
                {
                    # If found, delete it
                    Write-Host "    Quota template was located; deleting it..."
                    $service.QuotaTemplates.Delete($Name)

                    # Update the service
                    $service.Update()

                    #Report completion
                    Write-Host -f Green "Quota template $Name has been deleted."
                    Write-Host ""
                }
                else
                {
                    Write-Host -f Red "Quota template by name $Name was not found. Verify that it exists and name has been correctly typed in XML input."
                    Write-Host ""
                }
            }
        }
    }
}

ManageQuotaTemplates

This script is used to make changes to the quota templates currently defined within the system. This can be done by altering the XML file output generated by GetQuotaTemplates.ps1 shown above.

clip_image003

The Action attribute of the QuotaTemplate element can be altered to one of the following values.

 

Action Result
Add The script will attempt to create a new quota template. However if one already exists by the name used in the XML, no action is taken.
Edit The script will attempt to find an existing quota template by the given name and edit its properties. If one is not found, no action is taken.
Delete The script will attempt to find an existing quota template by the given name and delete it. If one is not found, script reports failure to find it.
None The quota template is left untouched.

Altering the XML

The following precautions need to be taken while altering the input file for the quota template management script

  1. Only edit the Action attribute on QuotaTemplate elements that need to be changed. It is None by default and these quota templates are not altered by the script.
  2. To add a new quota template, copy one of the existing elements over and change its attributes. Do not forget to set the Action attribute to Add.
  3. To edit an existing quota template, select the QuotaTemplate element with the corresponding Name attribute and change its attributes. Do not forget to set the Action attribute to Edit.
  4. To delete an existing quota template, select the QuotaTemplate element with the corresponding Name attribute and set its Action attribute to Delete.
  5. Add, Edit and Delete values on the Action attribute are case sensitive. Type exactly as shown here.
  6. Change the values of the attributes of the QuotaTemplate elements as necessary. Do NOT change any of the other XML constructs.
  7. Values for StorageMaxLevelInMB and StorageWarnLevelInMB are to be provided in integer megabytes. If you do not want to specify these, set them to zero.
  8. Values for UserCodeMaxLevel and UserCodeWarnLevel are to be provided in numerical points. If you do not want to specify these, set them to zero. If you want to set them to SharePoint standard values, specify 300 and 100 respectively.

Recommended approach

Run the GetQuotaTemplates.ps1 script first always to get a fresh updated XML from the server. Alter the XML as required and run ManageQuotaTemplates.ps1. The scripts have been written to avoid providing input parameters on the command line. Hope this helps.

Advertisements

PowerShell script to install SharePoint Root certificate to Trusted Root store

June 18, 2013 3 comments

Now this post is not really about why and how certificates are used by SharePoint. But in order to understand why we are doing what we are going to do shortly, let me start with a brief 2-minute (hopefully) primer on what this is about.

The public key infrastructure allows messages between users, applications and servers that host the applications to happen in a secure manner using digital certificates. The same happens within SharePoint when a message between entities needs to be secured. Now in order for the sender and receiver of messages secured through certificates to work, a trust needs to be established between the parties. The way this works is that both parties trust a third party which is the issuer of the certificate using which the message is signed. Bear in mind that this is a very high level overview of how this works and there are several variations that we shall not get into here. Having said the above, now in order for the receiver of a message to trust the certificate that is presented with it, it will need to be verified. Not only that certificate but its issuer’s certificate and that certificate’s issuer and so forth until we can trace back to a trusted root certificate. This is referred to as certificate chaining.

Within SharePoint, one instance where this happens is when the Security Token Service issues a token and signs it with a certificate. This certificate will need to be verified as mentioned above through building a chain back to a trusted root certificate. Also, a Certificate Revocation List (CRL) needs to be verified to ensure the certificate has not been revoked. This last is yet another topic requiring much detailed explanation that I shall try to address in a future post. But the idea here is that each certificate in the chain needs to be verified and one needs to lead to a trusted root CA store. If this doesn’t happen, certificate validation errors will occur and cause delays in response time to the users. To avoid this, we need to ensure that the SharePoint Root Authority certificate is installed to the Trusted Root Certification Authorities certificate store on each server in the SharePoint farm. The link above provides steps to do this but involves several manual steps. What I have included below, is a¬†PowerShell script that does it all end to end.

The following are prerequisites to running the script.

  • To be run locally on each machine.
  • To be run as a user with Shell_Admin_Access role on the farm databases [If this is not available run Add-SPShellAdmin before proceeding].
  • To be run as a user with local administrator privileges on the server.

Another thing worth verifying before executing the script is the execution policy on the server. You can determine this by running the Get-ExecutionPolicy cmdlet. This typically shouldn’t be a problem unless you are running the script from a remote share. If you do have a problem though, you can work around it by using the Set-ExecutionPolicy cmdlet.

function CopySharePointRootCertToLocalTrustedCertStore {

    # Add the SharePoint PowerShell snap-in
    if (-not (Get-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue)) {
	    Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    }

    # Get the SharePoint root certificate
    $rootCert = (Get-SPCertificateAuthority).RootCertificate

    # Store current location
    $location = Get-Location

    # Go to trusted root certificate store on local machine
    cd Cert:\LocalMachine\Root

    # Check if the certificate already exists
    # If it does, report and end
    if ((dir | ? { $_.Thumbprint -eq $rootCert.Thumbprint })) {
        Write-Host -f Green "SharePoint Root Authority already exists in local machine trusted root certificate store."
        cd $location
        return
    }

    # Get the certificate store for "Trusted Root Certification Authorities" (Cert:\LocalMachine\Root)
    $certStore = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store Root, LocalMachine

    # Open the store with maximum allowed privileges
    $certStore.Open("MaxAllowed")

    # Add the certificate to the store
    $certStore.Add($rootCert)

    # Close the store
    $certStore.Close()

    # Get the certificate if it exists
    if ((dir | ? { $_.Thumbprint -eq $rootCert.Thumbprint })) {
	    Write-Host -f Green "Certificate was successfully added to the Trusted Root store."
    }
    else {
	    Write-Host -f Red "The certificate could not be added to the Trusted Root store."
    }

    # Set location back to where it was
    cd $location
}

CopySharePointRootCertToLocalTrustedCertStore

You can save the script as a .ps1 file and run on each of the servers where the SharePoint root certificate needs to be copied. The way to verify that this has actually worked is to pull up a management console and add the Certificates snap-in as described in the Microsoft Support KB Article referenced above. If however, your objective is to just export the certificate from SharePoint, you may want to use the script provided below. Just make sure you set the $certPath to where you would actually like to export the certificate and by what name.

# Set the certificate file path
$certPath = "C:\SharePointRootAuthority.cer"

# Add the SharePoint PowerShell snap-in
if (-not (Get-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue)) {
	Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
}

# Get the SharePoint root certificate
$rootCert = (Get-SPCertificateAuthority).RootCertificate

# Export the certificate to disk as a certificate file
$rootCert.Export("Cert") | Set-Content $certPath -Encoding byte

Once you have exported the certificate, you can manually add it to the certificate store by using the Management Console or by using the second half of the first script presented above. The only difference is that you will need to construct an X509 certificate object from the certificate file as shown in the script snippet below.

# Set the certificate file path
$certPath = "C:\SharePointRootAuthority.cer"

# Get the certificate store for "Trusted Root Certification Authorities" (Cert:\LocalMachine\Root)
$certStore = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store Root, LocalMachine

# Get the certificate from the location where it was placed by the export process
$cert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 $certPath

# Open the store with maximum allowed privileges
$certStore.Open("MaxAllowed")

# Add the certificate to the store
$certStore.Add($cert)

# Close the store
$certStore.Close()

That’s it for now. Hopefully, I will find some time to write up more about troubleshooting certificates in SharePoint soon. In the meanwhile, happy scripting!

%d bloggers like this: