Wednesday, June 3, 2015

Powershell Script to delete sites and the corresponding sub-sites:

Powershell Script to delete sites and the corresponding sub-sites:

if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) {
    Add-PSSnapin Microsoft.SharePoint.Powershell
}


function RemoveSPWebRecursively(
    [Microsoft.SharePoint.SPWeb] $web)
{
    Write-Debug "Removing site ($($web.Url))..."
    
    $subwebs = $web.GetSubwebsForCurrentUser()
    
    foreach($subweb in $subwebs)
    {
        RemoveSPWebRecursively($subweb)
        $subweb.Dispose()
    }
    
    $DebugPreference = "SilentlyContinue"
    Remove-SPWeb $web -Confirm:$false
    $DebugPreference = "Continue"
}

$DebugPreference = "SilentlyContinue"
$web = Get-SPWeb "http://sitURL/Authoring/en-us"
$DebugPreference = "Continue"

If ($web -ne $null)
{
    RemoveSPWebRecursively $web
    $web.Dispose()
}

Monday, April 6, 2015

Getting public key token for a dll using PowerShell Script


Getting public key token for a dll using PowerShell Script:

([system.reflection.assembly]::loadfile("C:\Windows\Microsoft.NET\assembly\GAC_MSIL\GroupDropDownList\v4.0_1.0.0.0__22c2902360f8dd14\GroupDropDownList.dll")).FullName

It will give the result as:
GroupDropDownList, Version=1.0.0.0, Culture=neutral, PublicKeyToken=22c2902360f8dd14

Monday, February 16, 2015

Managed Metadata changes not applied to list items after changing the term Store Label

Problem:

Managed Metadata changes not applied to list items after changing the term Store Label. 

Sometimes you changed a term and you are wondering why the changed term cannot be seen in a List where you are using the terms in a column.

Consider the following scenario:
·   You are using Managed Metadata and administrate that within the central administration website.
·   You are using a List in a site and added a column to use Terms saved in the Managed Metadata database.
·   You changed a term in the taxonomy term store.
·   You may run manually the Taxonomy Update Scheduler job on the Scheduled Jobs central admin page or waited more than one hour; because the schedule of that job is set out of the box to run every hour.
·   You may see that the changed term has not been updated to the new value on the List where you are using those information.
·   You found the following entry in the ULS log:
·   Exception with ULS log entry:

Exception occurred while hidden list being updated: System.IO.FileNotFoundException: The site with the id 6c03a437-0d6d-44a3-a542-6235b854a36e could not be found.   
at Microsoft.SharePoint.SPSite..ctor(Guid id, SPFarm farm, SPUrlZone zone, SPUserToken userToken)   
at Microsoft.SharePoint.SPSite..ctor(Guid id)   
at Microsoft.SharePoint.Taxonomy.UpdateHiddenListJobDefinition.ProcessProxy(MetadataWebServiceApplicationProxy proxy)   
at Microsoft.SharePoint.Taxonomy.UpdateHiddenListJobDefinition.Execute(Guid targetInstanceId) 

Workaround:
To work around the issue and update the Taxonomy Hidden list manually you can use the following PowerShell script as follows.

Add-PSSnapin microsoft.sharepoint.powershell
$site=Get-SPSite <Site-URL>
[Microsoft.SharePoint.Taxonomy.TaxonomySession]::SyncHiddenList($site)
$site.dispose()

Thursday, February 12, 2015

Updating the User Profile Properties value by reading it from csv

Updating the User Profile Properties value by reading it from csv file:

The below script will read the username & update property from the csv file and update the user profile.

if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
  Add-PSSnapin Microsoft.SharePoint.PowerShell
}

$csvfile="c:\Temp\UserList.csv"
$mySiteUrl = "http://SiteURL"
$upAttribute = "Location"
$upUserName = "UserName"
$site = Get-SPSite $mySiteUrl
$context = Get-SPServiceContext $site
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
$csvData = Import-Csv $csvfile
foreach ($line in $csvData)
{
       if ($profileManager.UserExists($line.UserName))
       {
              $up = $profileManager.GetUserProfile($line.UserName)
              $up[$upUserName].Value + "|" + $up[$upAttribute].Value | out-file -filepath C:\temp\Before_UserUpdate.txt -append -width 200
              $up[$upAttribute].Value = $line.Location
              $up.Commit()
              $up[$upUserName].Value + "|" + $up[$upAttribute].Value | out-file -filepath C:\temp\After_UserUpdate.txt -append -width 200
             
        }
       else
       {
              $line.username | out-file -filepath C:\temp\UserNotFound.txt -append -width 200

        }
}

$site.Dispose()  

Thursday, February 5, 2015

Binding Term store/Term set in Dropdown control

Binding Term store/Term set in Dropdown control:


In .aspx.cs / .ascx.cs:

string siteURL = http://siteURL;

using (SPSite sSite = new SPSite(siteURL))
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb web = sSite.OpenWeb())
{
TaxonomySession txnSession = new TaxonomySession(sSite);

string strTermStoreName = "Managed Metadata Service";
TermStore termstore = txnSession.TermStores[strTermStoreName];

Group group = termstore.Groups["GroupName"];

TermSet tsRegion = group.TermSets["TermSet name"];
DataTable dtMMSRegion = GetTermSet(tsRegion.Terms);

DataView dvMMSRegion = new DataView(dtMMSRegion);
dvMMSRegion.Sort = "Name ASC";

ddlLocation.DataSource = dvMMSRegion;
ddlLocation.DataTextField = "Name";
ddlLocation.DataValueField = "Name";
ddlLocation.DataBind();
}
});
}




        protected DataTable GetTermSet(TermCollection tc)
        {
            DataTable dtMMSTermTable = new DataTable();

            dtMMSTermTable.Columns.Add("Name", typeof(string));

            DataRow drMMSTermRow;

            foreach (Term t in tc)
            {
                drMMSTermRow = dtMMSTermTable.NewRow();
                drMMSTermRow[0] = t.Name;
                dtMMSTermTable.Rows.Add(drMMSTermRow);
            }

            return dtMMSTermTable;

        }

In .aspx / .ascx

<asp:DropDownList ID="ddlLocation" AutoPostBack="true" EnableViewState="true" runat="server"></asp:DropDownList>

Friday, January 30, 2015

Delete Site Column and correnponding all references using PowerShell Script


Delete Site Column and correnponding all references using PowerShell Script:

Below Script is used to delete the Site Column and the corresponding References that uses the same Column:

# Add SharePoint PowerShell Snapin

if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) {
    Add-PSSnapin Microsoft.SharePoint.Powershell
}


    $siteUrl = 'http://siteURL/'

    $fieldName = 'ArticleSorting'

    Write-Host “Start removing field:” $fieldName -ForegroundColor DarkGreen
    $site = Get-SPSite $siteUrl
    $web = $site.RootWeb

    #Delete field from all content types
    foreach($ct in $web.ContentTypes) {
        $fieldInUse = $ct.FieldLinks | Where {$_.Name -eq $fieldName }
        if($fieldInUse) {
            Write-Host “Remove field from CType:” $ct.Name -ForegroundColor DarkGreen
            $ct.FieldLinks.Delete($fieldName)
            $ct.Update()
        }
    }
    
    #Delete column from all lists in all sites of a site collection
    $site | Get-SPWeb -Limit all | ForEach-Object {
       #Specify list which contains the column
        $numberOfLists = $_.Lists.Count
        for($i=0; $i -lt $_.Lists.Count ; $i++) {
            $list = $_.Lists[$i]
            #Specify column to be deleted
            if($list.Fields.ContainsFieldWithStaticName($fieldName)) {
                $fieldInList = $list.Fields.GetFieldByInternalName($fieldName)

                if($fieldInList) {
                    Write-Host “Delete column from ” $list.Title ” list on:” $_.URL -ForegroundColor DarkGreen

                 #Allow column to be deleted
                 $fieldInList.AllowDeletion = $true
                 #Delete the column
                 $fieldInList.Delete()
                 #Update the list
                 $list.Update()
                }
            }
        }
    }

    # Remove the field itself
    if($web.Fields.ContainsFieldWithStaticName($fieldName)) {
        Write-Host “Remove field:” $fieldName -ForegroundColor DarkGreen
        $web.Fields.Delete($fieldName)
    }

    $web.Dispose()
    $site.Dispose()

#Delete the field below
DeleteField http://siteURL/ $fieldName

Getting site content types and site columns using PowerShell


Getting site content types and site columns using PowerShell:

Add-PSSnapin Microsoft.SharePoint.PowerShell

## Variables

$WEB_APPLICATION_URL = "http://siteURL"
$CT_FIELDS_FILE_PATH = "c:\2013_CTs_And_Fields.csv"

## Initialization
echo "Initializing variables"

'"Site URL","Content Type","Field Name"' | Out-File $CT_FIELDS_FILE_PATH;

echo "Entering web application $WEB_APPLICATION_URL"
$webApplication = Get-SPWebApplication -identity $WEB_APPLICATION_URL
ForEach ($siteCollection in $webApplication.Sites)
{
    ForEach($subSite in $siteCollection.AllWebs)
    {
        $subsiteUrl = $subsite.Url;
        echo "Extracting info from $subSiteUrl";
        $contentTypes = $subSite.ContentTypes;
        ForEach ($contentType in $contentTypes)
        {
            ForEach ($field in $contentType.Fields)
            {

                '"'+ $subSiteUrl +  '","'  + $contentType.Name + '","' + $field.Title + '","' | Out-File $CT_FIELDS_FILE_PATH -Append;
            }
        }
    }
}
echo "Finished.....";


The script output is a set of three CSV files:
  1. Mapping between SiteURL, content types and fields