How to Delete the Blobs from the Azure Blob Container Using C# Programmatically

Sathish Nadarajan
 
Solution Architect
January 2, 2019
 
Rate this article
 
Views
14880

In the earlier article, we saw how to retrieve the Blobs from an Azure Container Using C#. In this article, as a continuation, let us see, how to delete them. This scenario is for clean up the Blobs during the development time. I faced this, when I needed to delete thousands of files from the Blob Container. It is not possible to delete one by one or on the page in the Azure Console, there is no select all option. Hence, did the clean-up programmatically.

The code is straight forward and a continuation of the earlier article itself.

 public static void DeleteFilesFromBlob()
         {
 //Set the connection string variable
             string storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=*****";
 
             // Retrieve storage account from connection string.
             CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
 
             // Create the blob client.
             CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
 
             // Retrieve reference to a previously created container.
             CloudBlobContainer container = blobClient.GetContainerReference("bwsacontainer");
 
 // Get the directory from which we need to delete the files
             CloudBlobDirectory dira = container.GetDirectoryReference("development21nov");
 
             //Gets List of Blobs
             var list = dira.ListBlobs();
             
             var blobNames = list.OfType<CloudBlockBlob>().ToList();
 
             foreach (var tempBlob in blobNames)
             {
                 tempBlob.FetchAttributes();
 //If we want to delete the files based on any filter, we can do as below.
                 //if (tempBlob.Properties.Length > 16000000)
                 //{
                     System.Console.WriteLine(tempBlob.Name);
                     tempBlob.Delete(DeleteSnapshotsOption.IncludeSnapshots);
                 //}
             }
             
         }
 
 

If we want to delete a specific file,

 // The below code is to delete a specific file
             var blob = dira.GetBlobReference("Stat_2018_11_21_10_35_03_p.m._can_(452).PDF");
             lob.FetchAttributes();
             
 blob.Delete(DeleteSnapshotsOption.IncludeSnapshots);
 
 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to Delete the Modern Sites Using PowerShell in SharePoint Office 365

Sathish Nadarajan
 
Solution Architect
September 7, 2018
 
Rate this article
 
Views
2853

 

In this article, a small PowerShell Snippet to delete the SiteCollections from Office 365 is explained.

There are two methods used in this script. Which is mandatory. Because, when we delete from the UI or only delete the site, the site will remain in the Recycle Bin. We need to clear the site from the Recycle bin as well. Otherwise, when we try to create again with the same site name, system will thrown an exception.

 

 # Delete the SiteCollection
 
 ##================================================================================================
 ## Description	: To Delete the Sitecollections
  
  
 ## Author		: Sathish
 ## Date			: 05-Apr-2018
 ##================================================================================================
 
 # ============================================ Setup Input Paths =================================
 
 cls
 
  
 $Host.UI.RawUI.WindowTitle = "-- Delete the Site Collection --"
 
 $StartDate = Get-Date
  
 Write-Host -ForegroundColor White "------------------------------------"
 Write-Host -ForegroundColor White "| Delete the Site Collection |"
 Write-Host -ForegroundColor White "| Started on: $StartDate |"
 Write-Host -ForegroundColor White "------------------------------------"
 
  
 
 ################# Set the Current Path as Execution Path ####################
 
 $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
 Set-Location $scriptBase
 
 ############# set the Error Preference ################
 
 $ErrorActionPreference = "Stop"
 
 
 $adminUrl = Read-Host "Enter the Admin URL of your Tenant"
 
 #connect to the Tenant Admin Site
 Connect-SPOService -Url $adminUrl
 
 try
 {
     #Delete the Site
     $siteURL = Read-Host "Enter the URL of the site to be deleted"
 
 
     #Delete the Site from the Tenant
     Remove-SPOSite -Identity $siteURL -Confirm:$false 
 
     #Delete the Site from the Recycle Bin 
     Remove-SPODeletedSite -Identity $siteURL -Confirm:$false 
 
     Write-Host -ForegroundColor Green $siteURL "Site Deleted Successfully" 
 }
 catch
 {
     cls
     Write-Host -ForegroundColor Red "Exception Occurred" 
     Write-Host -ForegroundColor Red $Error[0].Exception.Message
 }
 

 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Step by Step procedure to Create a Custom Action for Delete Button on SharePoint List Form Ribbon using JavaScript

Sriram
 
Technology Specialist
August 21, 2018
 
Rate this article
 
Views
5325

Recently I came up with requirement to change delete action’s confirmation message. Are you sure you want to send the item(s) to the Recycle Bin? to Are you sure you want to Cancel the Request? Also when clicking on the Delete icon, it should not delete the item; instead it should update the status of the item.

clip_image002

I have followed below approch to solve this problem.

Replace the ‘Delete Item’ button on the Ribbon bar with a copied ‘Delete Item’ button and then use ECMAScript and Sharepoint Client Object Model to remove the item and implement business logics.

Below are the steps to impelemet above functionality.

  1. Create 2 JS files for ViewForm and Edit Form,
  2. In the JS file under document.ready place the below code.

 

 $(document).ready(function(){
 //for view form
 var button = document.getElementById("Ribbon.ListForm.Display.Manage.DeleteItem-Medium");
 if (button != null) {
     var $button = $(button);
     var html = $button.html();
     $button.after("<div id='deleteIcon' OnMouseOver='ApplyCSSFunction()'><a style='cursor:pointer;'>" + html + "</a></div>").hide().next().click(function (e) {
 		DeleteCurrentItem();
     });
     $(".ms-cui-ctl-mediumlabel:eq(3)").css("vertical-align","top");
 	$(".ms-cui-ctl-mediumlabel:eq(3)").css("margin-left","4px");
 $('.ms-cui-ctl-mediumlabel:eq(3)').text("Cancel Request");
 	}
 
 $("#deleteIcon").mouseleave(function() {
  	  $("#deleteIcon").css("border-style","none");
         });
 });
 

 

  1. Write your business logic in DeleteCurrentItem() method.

 

 function DeleteCurrentItem()
 {
 $("#deleteIcon").css("border-style","none");
 var deleteConfirm = confirm("Are you sure you want to cancel this request?");
 if(deleteConfirm)
 {
  var deleteItemID=getParameterByName('ID');
  DeleteItem(deleteItemID);
 }
 }
 

 

  1. We need to change the highlighted line on the above code to make it work in Edit form.

View Form:

var button = document.getElementById(“Ribbon.ListForm.Display.Manage.DeleteItem-Medium”);

Edit Form:

var button = document.getElementById(“Ribbon.ListForm.Edit.Actions.DeleteItem-Large”);

Output:

clip_image004

Author Info

Sriram
 
Technology Specialist
 
Rate this article
 
Sriram T has been working in IT industry for over 6 years He holds Bachelor's degree in Computer Science Engineering. Sriram write articles and blogs related to SharePoint 2013, SharePoint ...read more
 

How to delete the Minor Versions of a Document Programmatically by C# CSOM

Sathish Nadarajan
 
Solution Architect
October 6, 2017
 
Rate this article
 
Views
4481

We were doing some migration and after the Migration, we were end up with a lot of Minor versions, which we did not create but the Migration tool created them. To remove the Minor versions, came up with a piece of script, thought of sharing to the community as well.

The below is the sample scenario.

clip_image002

I need to make sure that all the files are having only the Major Version. i.e., the File1.txt should be deleted with 1.1 and 1.2 Versions.

 using Microsoft.SharePoint.Client;
 using System;
 
 namespace Office365.Console
 {
     class Program
     {
         static void Main(string[] args)
         {
             DeleteMinorVersions();
         }
 
         public static void DeleteMinorVersions()
         {
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
             
             //Site URL
             string siteUrl = "https://*****.sharepoint.com/sites/communitysite";
             // UserName 
             string userName = "sathish@*******.onmicrosoft.com";
             //Password
             string password = "*********";
 
             
             using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
             {
                 try
                 {
                     Site site = clientContext.Site;
                     Web web = clientContext.Web;
                     
                     clientContext.Load(web);
                     clientContext.Load(web.Lists);
                     clientContext.ExecuteQuery();
                     //Get the Tasks List
                     List list = web.Lists.GetByTitle("MyDocumentsLibrary");
 
                     //Get the Child Item - The IDs were Hard coded for the demo purpose
                     ListItem listItem = list.GetItemById(20);
                     clientContext.Load(listItem);
                     clientContext.Load(listItem.File);
                     clientContext.Load(listItem.File.Versions);
                     clientContext.ExecuteQuery();
                     
                     if (listItem.File.Versions.Count > 0)
                     {
                         foreach (var ver in listItem.File.Versions)
                         {
                             if (!ver.VersionLabel.Contains(".0"))
                             {
                                 listItem.File.Versions.DeleteByLabel(ver.VersionLabel);
                                 clientContext.ExecuteQuery();
                             }
 
                         }
                     }
 
                 }
                 catch (Exception ex)
                 {
                     System.Console.ForegroundColor = ConsoleColor.Red;
                     System.Console.WriteLine("Exception Occured : " + ex.Message);
                     System.IO.File.AppendAllText("C:\Temp\Exception.txt", ex.Message + " - " + siteUrl + Environment.NewLine);
                 }
 
 
             }
 
 
             System.Console.WriteLine("Completed....");
             System.Console.WriteLine("Press Any Key to Exit ....");
             System.Console.ReadLine();
         }
          
 
          
     }
 }
 
 

 

 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to Delete/Update List/Library View in SharePoint Office 365 Programmatically using Patterns and Practices PNP

Sathish Nadarajan
 
Solution Architect
September 16, 2017
 
Rate this article
 
Views
2970

In the earlier article, we saw, how to Create a List View. In the same manner, we may come across a scenario to delete/update the existing views. The below snippet will be handy for the developers.

 using Microsoft.SharePoint.Client;
 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Reflection;
 
 namespace Office365.Console
 {
     class Program
     {
         static void Main(string[] args)
         {
             DeleteUpdateView();
         }
 
          
 
         public static void DeleteUpdateView()
         {
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
 
 
             string siteUrl = "https://************.sharepoint.com/sites/DeveloperSite/";
             //string siteUrl = item.TargetSiteUrl;
             string userName = "sathish@****.onmicrosoft.com";
             string password = "********";
 
             
             using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
             {
                 try
                 {
                     Web web = clientContext.Web;
                     
                     clientContext.Load(web);
                     clientContext.Load(web.Lists);
                     clientContext.ExecuteQuery();
 
                     List list = web.Lists.GetByTitle("Test List");
                     clientContext.Load(list);
                     clientContext.Load(list.Views);
                     clientContext.ExecuteQuery();
 
                     //To Delete the View 
                     var lstViewToBeDeleted = list.Views.GetByTitle("Created By Me");
                     lstViewToBeDeleted.DeleteObject();
                     clientContext.ExecuteQuery();
 
                     //To Update the View
                     var lstViewToBeUpdated = list.Views.GetByTitle("All Items Test");
                     lstViewToBeUpdated.ViewQuery = "<OrderBy><FieldRef Name="Modified" Ascending="FALSE" /></OrderBy>";
                     lstViewToBeUpdated.Update();
                     clientContext.ExecuteQuery();
                 }
                 catch (Exception ex)
                 {
                     System.Console.ForegroundColor = ConsoleColor.Red;
                     System.Console.WriteLine("Exception Occured : " + ex.Message);
                     System.IO.File.AppendAllText("C:\Temp\UpdatePropertyBagIndexed.txt", ex.Message + " - " + siteUrl + Environment.NewLine);
                 }
 
 
             }
 
 
             System.Console.WriteLine("Completed....");
             System.Console.WriteLine("Press Any Key to Exit ....");
             System.Console.ReadLine();
         }
          
 
          
     }
 }
 

In the above snippet, I have deleted a view and updated a view. The Update, I have done only the ViewQuery property. Like that, we can update many properties of a view and the ViewQuery itself, can have many CAML Queries.

The Output of the Update will be something like,

clip_image002

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Another site or list is still using this content type. If you would still like to delete it, please remove the content type from all sites and lists and then try again.

Sathish Nadarajan
 
Solution Architect
June 18, 2017
 
Rate this article
 
Views
3832

A small tip about deleting the Content Type. Usually all of us, will be trying to delete the Content type, before remove the association from the List and Libraries. At that time, we will get an error message stating that,

Another site or list is still using this content type. If you would still like to delete it, please remove the content type from all sites and lists and then try again.

 

image

 

Then, we will go back to the SiteCollection, remove the association, and delete the List/Library itself.

But even then, we will not be allowed to delete the Content Type. A simple mistake, at least every one of us would have done once. A simple stuff, we need to remember is, delete the List/Library from the Recycle Bin as well. Then, come back and delete the Content Type. It will allow us to delete the content type.

Happy Coding,

Sathish Nadarajan.

Category : Office 365, SharePoint

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to Delete a Permission Level in SharePoint Office 365 Programmatically using C# Client Side Object Model (CSOM)

Sathish Nadarajan
 
Solution Architect
April 10, 2017
 
Rate this article
 
Views
3316

In the earlier articles, (CREATE & ASSIGN) we saw how to create and assign the permission levels. In this article, let us see, how to delete a permission level. Usually, this will be required, when we create itself. i.e., Before Create any of the Permission Level, we should validate whether the permission level is already there or not. If it is already there, then based on our requirement, either we can delete and recreate or we can utilize the same. In our case, let us see, how to delete the permission level.

The below code has a Foreach loop to iterate all the RoleDefinitions. Actually that is not required if we know that there is a Role Definition is available. But if we are uncertain about the availability, it is always to use the Foreach.

 namespace Console.Office365
 {
     using Microsoft.SharePoint.Client;
     using System;
     using System.Collections.Generic;
     using System.Linq;
     using System.Text;
     using System.Threading.Tasks;
 
     class Program
     {
         static void Main(string[] args)
         {
             DeletePermissionLevel();
         }
 
         public static void DeletePermissionLevel()
         {
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
             string siteUrl = "https://***.sharepoint.com/sites/communitysite";
             string userName = "Sathish@****.onmicrosoft.com";
             string password = "*************";
 
 
             using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
             {
                 Web web = clientContext.Web;
                 clientContext.Load(web);
                 clientContext.Load(web.AllProperties);
                 clientContext.Load(web.RoleDefinitions);
                 clientContext.ExecuteQueryRetry();
                 var roleDefinitions = web.RoleDefinitions;
 
                 // Delete the Custom Permission Level if Already Exists
                 foreach (var roledefinition in roleDefinitions)
                 {
                     if (roledefinition.Name == "MyPermissionLevelCreatedByCode")
                     {
                         RoleDefinition customOwnersPermissionLevel = web.RoleDefinitions.GetByName("MyPermissionLevelCreatedByCode");
                         customOwnersPermissionLevel.DeleteObject();
                         clientContext.Load(web.RoleDefinitions);
                         clientContext.ExecuteQueryRetry();
                         break;
                     }
                 }
 
                  
 
             }
         }
 
     }
 }
 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to Delete Quick Launch to a Web Site in SharePoint Office 365 Programmatically using CSOM C#

Sathish Nadarajan
 
Solution Architect
January 29, 2017
 
Rate this article
 
Views
2910

In this article, we will be seeing how to Delete Quick Launch to a Web in SharePoint Office 365 Programmatically using CSOM C#

 namespace Console.Office365
 {
     using Microsoft.SharePoint.Client;
     using Microsoft.SharePoint.Client.Taxonomy;
     using Newtonsoft.Json.Linq;
     using System;
     using System.Collections.Generic;
     using System.IO;
     using System.Linq;
     using System.Threading.Tasks;
 
     class Program
     {
         static void Main(string[] args)
         {
             DeleteQuickLaunch();
         }
 
         public static void DeleteQuickLaunch()
         {
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
             string siteUrl = "https://*******.sharepoint.com/sites/communitysite/";
             string userName = "Sathish@******.onmicrosoft.com";
             string password = "**********";
 
             using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
             {
                 Web web = ctx.Web;
                 ctx.Load(web);
 
                 NavigationNodeCollection quickLaunchCollection = web.Navigation.QuickLaunch;
                 ctx.Load(quickLaunchCollection);
                 ctx.ExecuteQueryRetry();
 
                 NavigationNode NavigationNode = quickLaunchCollection.Where(n => n.Title == "Heading4").FirstOrDefault();
 
                 NavigationNode.DeleteObject();
 
                 ctx.ExecuteQueryRetry();
             }
         }
     }
 }
 
 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

How to Remove/Delete Event Receivers to a Web in SharePoint Office 365 Programmatically using CSOM C#

Sathish Nadarajan
 
Solution Architect
January 24, 2017
 
Rate this article
 
Views
4908

In this article, we will be seeing how to Remove / Delete the Event Receiver to a Web in SharePoint Office 365 Programmatically using CSOM C#

 namespace Console.Office365
 {
     using Microsoft.SharePoint.Client;
     using Microsoft.SharePoint.Client.Taxonomy;
     using Newtonsoft.Json.Linq;
     using System;
     using System.Collections.Generic;
     using System.IO;
     using System.Linq;
     using System.Threading.Tasks;
 
     class Program
     {
         static void Main(string[] args)
         {
             DeleteEventReceivers();
         }
 
 
         public static void DeleteEventReceivers()
         {
             OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
             string siteUrl = "https://*********.sharepoint.com/sites/CommunitySite/";
             string userName = "Sathish@*****.onmicrosoft.com";
             string password = "*********";
 
 
 
             using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
             {
                 Web web = ctx.Web;
                 ctx.Load(web);
                 ctx.Load(web.EventReceivers);
                 ctx.ExecuteQueryRetry();
 
                 #region Remve / Delete Document List Created Event Receiver
 
                 foreach (var eventRecevier in web.EventReceivers)
                 {
                     if (eventRecevier.ReceiverName == "<<Receiver Name>>")
                     {
                         eventRecevier.DeleteObject();
                         ctx.Load(web);
                         ctx.ExecuteQueryRetry();
                         break;
                     }
                 }
 
                 #endregion
 
                 System.Console.ReadLine();
             }
         }
 
 
     }
 
 }
 
 

Happy Coding,

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Deleting SiteColumns and Remove From Content Types, Lists Using PowerShell in SharePoint 2013

Sathish Nadarajan
 
Solution Architect
December 23, 2014
 
Rate this article
 
Views
29515

We saw how to create the Site Columns in last post. Now, let us see, how to remove them from the site through PowerShell.

Again, this will also have the same CSVs and PS1 file.

SiteUrlSiteColumnInternalNameSiteColumnDisplayName
http://C4968397007:1001/sites/DemoAdminDemoTaxonomyFieldDemo Taxonomy Field
http://C4968397007:1001/sites/DemoAdminDemoTextFieldDemo TextField
http://C4968397007:1001/sites/DemoAdminDemoChoiceFieldDemo ChoiceField

This CSV will have the Site and the Internal Name of the Site Column.

SiteUrlSiteColumnInternalName
http://C4968397007:1001/sites/DemoAdminDemoTaxonomyField
http://C4968397007:1001/sites/DemoAdminDemoTextField
http://C4968397007:1001/sites/DemoAdminDemoChoiceField

Again, the above would be the input for the second portion. i.e., from the Content Types and the List, and from the Web Itself, the site column would be deleted.

The script as follows.

 $LogTime = Get-Date -Format yyyy-MM-dd_hh-mm
 $LogFile = ".RemoveSiteColumnReferencePatch-$LogTime.rtf"
 
 cls
 
 $ErrorActionPreference = "SilentlyContinue"
 
 #start-transcript $logfile
 
 # Add SharePoint PowerShell Snapin
 
 
 if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) {
     Add-PSSnapin Microsoft.SharePoint.Powershell
 }
 
 $scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
 Set-Location $scriptBase
 
  
 
 ######################Functions###################################################
 
 function RemoveSiteColumnReferenceInCT([string]$siteUrl, [string]$fieldName, [string]$SiteColumnDisplayName) 
 {
     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 "The site column " $fieldname " is referenced in " $ct.name -fore yellow
             Write-Host "Remove Site column " $fieldname " which is referenced in CType: " $ct.Name -ForegroundColor DarkGreen
             $ct.FieldLinks.Delete($fieldName)
             $ct.Update()
 	        Write-Host "Site column " $fieldname " referenced in CType: " $ct.Name " is successfully removed............ Done !" -ForegroundColor Green
         }
     }
 
     $web.Dispose()
     $site.Dispose()
 }
 
 
 function RemoveSiteColumnListReference([string]$fieldName, [string]$SiteColumnInternalName) {
 
     get-spsite -limit all | Get-SPWeb -Limit all | ForEach-Object {
        
         $numberOfLists = $_.Lists.Count
         for($i=0; $i -lt $_.Lists.Count ; $i++) 
         {
             $list = $_.Lists[$i]
             
             if($list.Fields[$fieldName]) 
             {
                 $fieldInList = $list.Fields[$fieldName].InternalName
                 if($fieldInList -eq $SiteColumnInternalName) 
                 {
                     $_.URL + "," + $list.Fields[$fieldName] + "," + $fieldInList + "," + $list.Title | Out-File -Encoding Default -Append -FilePath $Output1;
                     Write-Host "Deleting Site column " $list.Fields[$fieldName] " from " $list.Title ” list on:” $_.URL -ForegroundColor cyan
 		            $fieldInList1 = $list.Fields.getfieldbyinternalname($SiteColumnInternalName)
                  
               		$fieldInList1.AllowDeletion = $true
                  
               		$fieldInList1.Delete()
 		            
                     Write-Host "Site column " $fieldName " referenced in list " $list.Title " is removed from " $_.URL " ........... Done ! "  -ForegroundColor Green
                  
               		$list.Update()
                 }
             }
         }
     }
     
 }
 
 
  
 
 function RemoveSiteColumn([string]$SiteUrl, [string]$fieldName)
 {
     $site = Get-SPSite $SiteUrl
 
     $web = $site.RootWeb
     $column = $web.Fields.getfieldbyinternalname($fieldName)
     if($Column)
     {
         write-host "Deleting site column " $fieldName " in site " $web.url -fore yellow
         $Column.Delete()
         write-host "site column " $column.Title " deleted successfully from the site " $web.url ".......... Done !" -fore blue
     }
 }
 
  
 
 ######################End of Functions###################################################
 
 
 ######################Calling Functions###################################################
 
 $SiteColumnDetails = $scriptBase + "" + "01.SiteColumnDetails.csv"
 $RemoveSiteColumns = $scriptBase + "" + "02.RemoveSiteColumns.csv"
 
 
 
 ##################Remove site column reference in content type############################
 
 import-csv $SiteColumnDetails | where {
     RemoveSiteColumnReferenceInCT $_.SiteUrl $_.SiteColumnInternalName $_.SiteColumnDisplayName
 }
  
 
 
 ##################Remove site column reference in List####################################
 
 import-csv $SiteColumnDetails | where {
     RemoveSiteColumnListReference $_.SiteColumnDisplayName $_.SiteColumnInternalName
     sleep(2)
 }
 
 
 ##################Remove site column#######################################################
 
 import-csv $RemoveSiteColumns | where {
     sleep(10)
     RemoveSiteColumn $_.SiteUrl $_.SiteColumnInternalName
 }
 
  
 #stop-transcript 
 
 
Download Script HERE 

Happy Coding.

Sathish Nadarajan.

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment