Tuesday, January 17, 2012

Powershell script to modify List Item Create/Edit Permissions

Recently I came across a very interesting requirement in one of our SharePoint 2010 projects.

Requirement: Customer wanted to lock down/prevent Site wide Members/Contributors from creating, modifying/editing and deleting List Items for the first 10 days of every month.

Solution: Here are the options to meet the above requirements:

1. Write a C#.NET utility (.exe) using SP 2010 object model to Revoke and Grant List Item Permissions and schedule it using the Task Scheduler on your SharePoint farm.

2. Program against the SharePoint web service to create a utility (.exe) that Revokes/Grants List item permissions and schedule it using the Task Scheduler in your remote system.

3. Write 2 Powershell scripts to Revoke and Grant List Item Permissions and create batch file to call the .ps1, then schedule it using the Task Scheduler on your SharePoint farm.

We went for option 3, i.e. Creation of Powershell scripts, as this is one of the most preferred and easiest of all the above mentioned solutions. Also we were allowed to copy/paste scripts to our SharePoint 2010 Server Farm, so that helped additionally and we were able to meet the customers requirements without any code/utility deployments in our SharePpint farm.

We will first write the script for Revoking List Item Permissions as it needs to be scheduled on 1st of every month:

1. Copy the powershell script below and modify the variables highlighted in yellow below, save the following as RevokeListIitemEditPermissions.ps1 file:

Add-PsSnapin "Microsoft.SharePoint.PowerShell"

## SharePoint DLL Reference
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration")

#Change the Web URL to point to the site/subsite where your List exists and the list name
$web = Get-SPWeb "http://dev-sp-2010:1000/sites/SPFix/"
$listName = "List Security"

#Check If the Web is null
if ($web -ne $null)
{
#Get the list in this site
$list = $web.Lists[$listName]

if($list -ne $null)
{
#Revoke Create and Edit permissions for the Current List
#4 — Users cannot modify any list item.
$list.WriteSecurity = 4

#Update the list
$list.Update()

#Update the web
$web.Update()

echo "Revoked Edit Items Permissions on the list"
}
else
{
echo "List is null. Check the List Name."
}

#Dispose of the site object
$web.Dispose()
}
else
{
echo "Web is null. Check the Web URL."
}

Remove-PsSnapin "Microsoft.SharePoint.PowerShell"

2. To automatically run the above .ps1 script as a batch utility, Copy and paste code below and save it with a .bat file extension

cd /d %~dp0
powershell -noexit -file ".\RevokeListIitemEditPermissions.ps1" "%CD%"
pause

We will now write the Grant List Item Edit Permissions to grant back the List Item Create, Edit and Delete privileges for all Contributors/Members for the List. This needs to be scheduled on 10th of every month.

3. Copy the powershell script below and modify the variables highlighted in yellow below, save the following as GrantListIitemEditPermissions.ps1 file:

Add-PsSnapin "Microsoft.SharePoint.PowerShell"

## SharePoint DLL Reference
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration")

#Change the Web URL to point to the site/subsite where your List exists and the list name
$web = Get-SPWeb "http://dev-sp-2010:1000/sites/SPFix/"
$listName = "List Security"

#Check If the Web is null
if ($web -ne $null)
{
#Get the list in this site
$list = $web.Lists[$listName]

if($list -ne $null)
{
#Grant Create and Edit permissions for the Current List
#2 — Users can modify only items that they create.
$list.WriteSecurity = 2

#Update the list
$list.Update()

#Update the web
$web.Update()

echo "Granted Edit Items Permissions on the list"
}
else
{
echo "List is null. Check the List Name."
}

#Dispose of the site object
$web.Dispose()
}
else
{
echo "Web is null. Check the Web URL."
}

Remove-PsSnapin "Microsoft.SharePoint.PowerShell"

4. To automatically run the above .ps1 script as a batch utility, Copy and paste code below and save it with a .bat file extension

cd /d %~dp0
powershell -noexit -file ".\GrantListIitemEditPermissions.ps1" "%CD%"
pause

Last but not the least schedule the 2 batch files by going to the Windows Task Scheduler and Create a Task.

You need to create 2 tasks, first one for Revoking the List Item Edit permissions that Triggers on 1st of every month and 2nd one to Grant List Item Edit Permissions that Triggers on 10th of every month. In the Actions section of the Task scheduler, give reference to the batch files created above one by one. The batch files in-turn calls the .ps1 according to the jobs scheduled every month.

Happy Programming :)

Saturday, January 14, 2012

Powershell script to print User Profile properties in a .csv file


Here is the powershell script to print all User Profile properties for a SharePoint farm and print them into a .csv file


1. Copy the code below and modify the variables highlighted in yellow below, save the following as PrintAllUserProfileProperties.ps1 file:

param
(
    $siteAddress
)

Add-PsSnapin "Microsoft.SharePoint.PowerShell"
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")

try
{
    $site = New-Object Microsoft.SharePoint.SPSite $siteAddress
    $context = [Microsoft.SharePoint.SPServiceContext]::GetContext($site)
    $configManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileConfigManager $context
    $propertyManager = $configManager.ProfilePropertyManager
    set-variable -option constant -name out -value "C:\PrintAllUserProfileProperties.csv"

    foreach ($codeProperty in $propertyManager.GetCoreProperties())
    {
        if (!$codeProperty.IsSection)
        {
            $codeProperty.DisplayName + " - " + $codeProperty.Name | Out-File $out -append
        }
    }
}
finally
{
    if ($site -ne $null)
    {
        $site.Dispose()
    }
}

Echo "Finished!"
Echo "User Profile properties printed at:" $out

Remove-PsSnapin "Microsoft.SharePoint.Powershell"

2. To automatically run the above .ps1 script as a batch utility, Copy and paste the code below and save it with a .bat file extension, kindly make sure you update the siteAddress switch with the relevant farm URL

cd /d %~dp0
powershell -noexit -file ".\PrintAllUserProfileProperties.ps1" -siteAddress "http://dev-sp-2010:1000/sites/SPFix" "%CD%"
pause

Run the above .bat file, on the receipt of success message, traverse to the configured path and find the .csv file with all the user profile properties printed.

Thursday, December 1, 2011

PowerShell script for creation of Custom Event Source and Event Log

Copy the PowerShell script below and save it as EventSourceCreation.ps1 for creation of Event Source and Event Log:

#Write-Host "Remove event source SharePointEventSource"
Remove-EventLog -Source SharePointEventSource
#Write-Host "SharePointEventSource removed"

#Write-Host "Create event source SharePointEventSource"
New-EventLog -LogName "SharePoint Event Source" -Source SharePointEventSource
#Write-Host "Event source SharePointEventSource created"

Once event source has been created, go to Run => eventvwr and you will see that the new
"SharePoint Event Source" has be created under the Application and Services Logs, see snapshot below:

To automatically run the above script as a batch utility, copy and paste the code below and save it as a .bat file extension:

cd /d %~dp0
powershell -noexit -file ".EventSourceCreation.ps1" "%CD%"
pause

Can write custom logging in SharePoint using the SPDiagnosticsService class to log messages and exceptions against the above custom source created namely: SharePointEventSource

Run the script and enjoy :)

Thursday, November 10, 2011

Programmatically find SharePoint 2010 Web Control references in your code-behind files


Programmatically find SharePoint 2010 Web control references in the code-behind files like .aspx.cs for Page Layouts or Custom Application Pages and .ascx.cs for User Controls and Visual Webparts.

I tried to get a handle to the RichHtmlField control in SharePoint using the standard .NET way like this:
Control ctrl = this.FindControl("controlID") as Control;

Sadly it did not work.

So had to write a generic FindControlRecursive methods to get a reference to any SharePoint Web Control used in Page Layouts, Application Pages, Visual WebParts, User Controls etc. See the function call and the generic functions. Copy the code and use it to your advantage.

Function call:

RichHtmlField pageContent = FindControlRecursive(this.Page, "pageContent") as RichHtmlField;

Generic Methods:

         private static Control FindControlRecursive(Page page, string controlID)
        {
            foreach (Control controlToSearch in page.Controls)
            {
                Control controlToReturn = FindControlRecursive(controlToSearch, controlID);

                if (controlToReturn != null)
                {
                    return controlToReturn;
                }
            }

            return null;
        }
     

        private static Control FindControlRecursive(Control rootControl, string controlID)
        {
            if (String.Equals(rootControl.ID, controlID))
            {
                return rootControl;
            }

            foreach (Control controlToSearch in rootControl.Controls)
            {
                Control controlToReturn = FindControlRecursive(controlToSearch, controlID);

                if (controlToReturn != null)
                {
                    return controlToReturn;
                }
            }

            return null;
        }

Hope it helps. Happy Programming.

Wednesday, September 21, 2011

Powershell script to print Managed Metadata termsets in a .csv file

Here is the powershell script to retrieve all Managed metadata term sets for a SharePoint 2010 site collection and print them into a .csv file

1. Copy the code below and modify the variables highlighted in yellow below, save the following as PrintManagedMetadataTerms.ps1 file:

Add-PsSnapin "Microsoft.SharePoint.PowerShell"

$site = Get-SPSite "http://dev-sp-2010:1000/sites/sharepointfix/"
$termStoreName = "Managed Metadata Service"
$termStoreGroupName = "SharePointFixPortal"

set-variable -option constant -name out -value "C:\PrintAllManagedMetaDataTermSets.csv"

$session = new-object Microsoft.SharePoint.Taxonomy.TaxonomySession($site)
$termStore = $session.TermStores[$termStoreName]
$termStoreGroup = $termStore.Groups[$termStoreGroupName]

# Prints all Managed Metadata Termsets in the .csv file at the configured location
foreach($termsets in $termStoreGroup.TermSets)
{
"Termset Name: " + $termsets.Name + ", Description: " + $termsets.Description + ", Group: " + $termsets.Group + ", ID: " +$termsets.Id + ", Available for Tagging: " + $termsets.IsAvailableForTagging + ", Is Open for Term Creation : " + $termsets.IsOpenForTermCreation | Out-File $out -append;

foreach($terms in $termsets.GetAllTerms())
{
"Term Name:" + $terms.Name | Out-File $out -append
}
}

$site.Dispose()

Echo "Finished!"
Echo "Managed metadata termsets printed at:" $out

Remove-PsSnapin "Microsoft.SharePoint.Powershell"

2. To automatically run the above .ps1 script as a batch utility, Copy and paste code below and save it with a .bat file extension

cd /d %~dp0
powershell -noexit -file ".\PrintManagedMetadataTerms.ps1" "%CD%"
pause

Run the above .bat file, on the receipt of success message, traverse to the configured path to find the .csv file with all the managed metadata printed values.