PowerShell Automation: How to Send Email Notifications

While developing some of the automation tools I was required to send emails to the intended users sometimes to inform them about the operational progress or otherwise.

In this article I will take you through the steps to develop PowerShell functions that can send emails to the intended participants.

Let’s look into the code base used for this article-

Step – 1: This will be the final step where we are calling the “Send-Email” function, implementation of which can be seen in the upcoming steps.

Step – 2: In this step I have shown the distribution list comprising of intended participants, here in this article I choose to make it hard coded with in the code which is an absolutely bad idea J and should be avoided. Rather we should have external content source (CSVs, SharePoint Lists) to configure this list of intended recipients.

Step – 3: In this step we have declared a variable holding subject for the email

Step – 4: In this step we prepare the body of the email. It is worth noting that you can use any valid HTML to prepare the mail body. Make sure you don’t use CSS Classes as they won’t work here. You can use inline styles to format the html.

Step – 5: In this step we will call the helper function and pass on the data we have prepared in previous steps. This function has the responsibility to send the email to the required recipients.



Step – 6: In this step we get the Sender’s Id. As a part of the best practice this should be a generic Id.

Step – 7: In this we get SMTP Server Address to relay through the mail

Step – 8: In this step we are creating the array of recipient since “Send-MailMessage” function uses Array as parameter return type to “-To” parameter.

Step – 9: In this step we are calling “Send-MailMessage” function by passing required parameters as shown below-


That’s all for the code.

On successful execution we will get a new email in the Inbox as shown below-


That is all for this simple demo.

Hope you find it helpful.

SharePoint Online/2016/2013: How To Upload Large Files Using PowerShell Automation

Uploading large files to SharePoint On-Premise or Online is an obvious problem during data migration from any external systems like Lotus Notes.

Here is one of such errors which we might encounter while trying to upload a file of size greater than 250 MB-


In this article I will explain a data upload strategy where we can split a large file into multiple chunks of smaller size.

Solution Architecture Diagram

For better understanding we can refer to the following solution architecture diagram-


Based on this diagram we can conclude the following facts-
1. This solution can be hosted on multiple servers to launch parallel uploads
2. This solution can consume data from Network File Shares
3. Once data file is retrieved (say of size 300 MB), this solution will split the file (100 MB) automatically based on the pre-configured chunk size (which should not exceed the size limit of 250 MB)
4. Each chunk then appended to the file uploaded in multiple iterations

In order to start with this demo we would need a SharePoint Document Library in SharePoint Online (or On-Premise) Site as shown below-


Another prerequisite to demo is to have files of various sizes that we can use to upload to the document library.

I made use of following command line utility to generate files of various sizes. This utility takes destination folder path and size of the file in KBs as input.

Here is the usage example of the command line utility-

fsutil file createnew "C:\Prashant\Self Paced Training\Sample Files\2GB.txt" 2147483648

Similarly I have generated other files too as shown below-


Now let’s dive down into the code to understand the actual implementation.

Step 1: Declare a variables to hold the document library name & folder path. For production use I recommend to have these values in an external configuration file.

Step 2: Reading files from the folder specified in path variable in Step 1

Step 3: Loop through all the files and pass each file to the “UploadLargeFiles” function along with the document library name


Step 4: Generate unique upload id & get file name of the file to be uploaded

Step 5: Get handle on document library object and load the root folder (or any target folder) with in the document library

Step 6: Calculate the block size to be uploaded and total file size (as shown in the architecture diagram)

Step 7: Read the bytes from the source file and set the read buffer based on the block size


Step 8: Read the bytes based on the buffer limit that we set in earlier steps


Step 9: Check if this is the first chunk that is being uploaded, if yes then add a new file to SharePoint Document Library, get the file content based on the buffer size for the chunk and call “StartUpload” function that is defined under “Microsoft.SharePoint.Client.File” class. This will add the file to the document library but with small bunch of content only.

Step 10: Check if this is not the first chunk that is being uploaded, if yes then find the file in document library and get the handle on it

Step 11: If this is another chunk of data which is not the last chunk, this chunk will be appended to the same file by using “ContinueUpload” function that is defined under “Microsoft.SharePoint.Client.File” class. This will append the content to the file identified by Upload Id that we have initialized in earlier steps.

Step 12: If this is last chunk of data, this chunk will be appended to the same file by using “FinishUpload” function that is defined under “Microsoft.SharePoint.Client.File” class. This will append the content to the file identified by Upload Id that we have initialized in earlier steps and commits the changes to the file. Once this function completes successfully the changes will be made persistent to the file.


Step 13: Perform exception handling and call the “UploadLargeFileToLibrary”


I recommend to read the documentation on Microsoft.SharePoint.Client.File class and understand functions carefully before using it.

Once we execute this script we can see the following information-

  1. File Name to be uploaded
  2. Chunk size
  3. Total Time taken to upload the files

It is important to note that total time taken to upload the files may vary depending on the hosting environment.

File Size to be uploaded: 10 MB


File Size to be uploaded: 50 MB


File Size to be uploaded: 500 MB


File Size to be uploaded: 2 GB


Once the script executed successfully we can see the respective files uploaded to the SharePoint Online Site as shown below-


That is all for this demo.

This article is equally applicable for both SharePoint Online & On-Premise Versions.

Hope you find it helpful.

SharePoint 2013/2016: How to Find Duplicate Records in SharePoint List

During one of my assignments I have come across a situation where we need to fix data issues in SharePoint Lists.

One of the issues that we found was presence of duplicate data. In order to fix that problem in hand I had developed a Powershell Script to find out duplicate data based on a specific or a group of columns.

For the sake of demo, I have added a SharePoint List with some duplicate records in it as shown below:


Now let’s look into the code to understand implementation details-

In Step 1 we are getting references of the Site and Web where the SharePoint List resides

In Step 2 we are splitting the list of columns based on which we want to find out the duplicate data

We can see there are two input variables “ColumnToValidate” and “ColumnToDisplay”. “ColumnToValidate” provides columns based on which duplicity needs to be checked while “ColumnToDisplay” contains the list of columns that needs to be the part of data export.

In Step 3 we are creating the export folder that will hold the CSV files exported with duplicate records

In Step 4 we are creating the list object that will give the handle on the list which needs to be validated


In Step 5 we are getting list of Items from SharePoint List and grouping them based on the validation columns

In Step 6 we are creating the directory for export files

In Step 7 we are exporting all the groups which is having item count greater than 1 (this logic identifies the duplicate items)


That is all for the code.

Now we will see the variation in outputs depending on the columns specified for duplicacy check

In Step 8 we specify the validation and display columns, for the first execution we will check duplicate values in “Title” column

In Step 9 we are calling the “Get-DuplicateListItems” function to find the duplicate values


After the function executed successfully we can see the following output.

In Step 10 we can see the output of this excution and can see 6 items found which duplicate in Title Column


In Step 11 we can see the CSV file that is exported by the execution considering “Title” Column to be validated.


In Step 12 we can see the output file and can notice duplicate values in “Title” Column


In Step 13 we have changed the list of columns to be validated. In this second execution I have added another column “Role”.

Now the list will be validated for duplicity based on the combination of “Title & Role” Columns


In Step 14 we can see the output of this excution and can see 4 items found which duplicate in “Title & Role” Columns


In Step 15 we can see the CSV file that is exported by the execution considering “Title & Role” Column to be validated


In Step 16 we can see the output file and can notice duplicate values in “Title & Role” Column


In Step 17 we have changed the list of columns to be validated. In this second execution I have added another column “Location”.

Now the list will be validated for duplicity based on the combination of “Title & Role & Location” Columns


In Step 18 we can see the output of this excution and can see 2 items found which duplicate in “Title & Role & Location” Columns


In Step 19 we can see the CSV file that is exported by the execution considering “Title & Role & Location” Column to be validated


In Step 20 we can see the output file and can notice duplicate values in “Title & Role & Location” Column


This is a very simple technique that can be used to fix one of the issues with SharePoint List data.

Hope you find it helpful.

SharePoint 2016/2013/Online- How to Apply Password Encryption for Component as Service using PowerShell

Recently I have developed a couple of PowerShell based components that will serve as data crawlers for federated data sources like External Web Services, SQL Server Databases, and Excel Workbooks & SharePoint Lists.

In order to authenticate the Service Accounts against all of these sources I had no choice but to embed the User Name and Passwords with in the PowerShell Code in plain text. It gets even worst when few of the Web Services could support only “Basic Authentication”.

Saving passwords in plain text to code files could lead us to the Compliance Issues and could get the solutions rejected eventually.

In order to fix this issue I have implemented a couple of mechanism to deal with each type of Authentication requirements.

In this article I will discuss the mechanism to authenticate the requests to SharePoint Lists.

In order to simplify this demo let’s consider a simple scenario where I am having a list “MyLocations” as shown below and I need to export its metadata using a PowerShell based component.


To keep the content crisp I will walk you through the specific section from code and skipping all the CSOM specific code which you can refer in my earlier articles if you like.

I have intentionally divided this implementation into two separate code files in order to keep the passwords safe from the developers. Intent is to get the Encryption File generated by the SharePoint Admins and provided these files to developers for so that they can use it in code directly as shown below.

In the following code snippet you can see the commands to encrypt password “12345678” and export it to a text file “BANSALP.txt”


This file would look like as shown below:


This way you can store passwords for all required service accounts in different text files without violating Security Compliance.

Now in order to pass this encrypted password to SharePoint for authentication we can make use of “System.Management.Automation.PSCredential” Class as shown below.

Here “Get-Content” Command let is used to read the content from “BANSALP.txt” file and “ConvertTo-SecureString” Command let to get the encrypted password as secure string


Once credential Object has been created we can assign this credential object to SharePoint Client Context “Credentials” Property


With this Client Context SharePoint Authenticates the incoming request based on the ACL of the requestor

Following is the outcome of the call that we have send to SharePoint:


I have exported the metadata to a “csv” file as well that would look like this.


Hope you find it helpful.

Create Windows Scheduler Task by PowerShell Automation

In this article we will see simple steps to configure windows scheduler tasks using PowerShell Automation.

This article can be useful in conjunction with some of the earlier articles that I have written on Process Automation using PowerShell

Before getting into the code, let see the Windows Task Manager to understand where we can find tasks which are getting created by the code

Type “Task Manager”


You can see the highlighted section where you can find newly created Tasks


The code is pretty simple and based on standard PowerShell Command-lets as described below:


In Step 1, we are defining Trigger for the Task by using “New-ScheduledTaskTrigger” Command-Let. It could be any permissible Time Unit as shown below


In Step 2 & 3 we are setting up User Name and Password that the Task will be used as Owner Account to run the defined action

In Step 4 we are defining the action by using “New-ScheduledTaskAction” Command-Let that needs to be executed by the task when trigger reached, in this demo this task will execute a PowerShell script

Finally in Step-5 we are registering the tasks by using “Register- ScheduledTask” Command-Let. This Command-Let takes Name, Trigger, UserName, Password and Action as input parameter (as defined in above steps)

Once the script gets executed a new task will be added to the Windows Task Scheduler


We can see the new task added in Task Scheduler Window as shown below:


If we double click the this task, it will open the task configuration screen that we can use verify the task properties as explained below-

General Tab: Here we can see the name of the Task & User Account that will be used to execute the defined action


Triggers Tab: Here we can see the Trigger defined for this task


Actions Tab: Here we can see the action defined for this task. In this demo we have specified a PowerShell Script to be executed whenever respective trigger achieved


In case if you make any changes to this task Windows will present you a password dialog to confirm the User Credentials, If asked enter the respective credentials


This is a simple implementation that allows you to configure Windows Tasks using PowerShell Automation.

That is all for this demo.

Hope you find it helpful.

SharePoint 2016/2013 : Event Log Monitoring by PowerShell Automation

This article is based on the requirement I recently encounter where I was required to monitor a specific exception type and if it occurs the Admins should be notified at the same time.

In this demo I am considering a scenario that if ever we have encountered an Event ID “1101” that would mean the SharePoint Site or any related service is down and in that case the Administrators will get Email Notifications automatically.


In order to accomplish this let start with writing a PowerShell function “Monitor-Event-Logs” as shown in Step 1

In Step 2 we are making use of “Get-EventLog” commandlet by instructing it to get the top 1 latest Application Log where the Event ID = “1101”

We can check for Event Object for null and if it returns the data  we prepare the Email Content comprising of relevant data in as shown in Step 3

In Step 4 we are sending Email Notification to the Administrators by using another generic function “Send-Email”


There is an external function “Execute-Process” that will call the “Monitor-Event-Logs” function by passing required Event ID as shown in Step 5

In Step 6 we are initializing the required variables pointing to the email ids of the respective contact persons

Finally in Step 7 we will call the “Execute-Process” function that will drive the whole mechanics.


Once the function gets executed we can see the email arrived notifying the error to the administrators as shown below:


To make this process more intuitive I got this script scheduled using Windows Task Scheduler to run on a specific time intervals and scan the logs for specific Event IDs.

In my actual implementation I design the “Monitor-Event-Logs” function to accept an array of Event IDs to be monitored so you can try it that way depending on your requirements.

Hope you find it helpful.




SharePoint 2016/2013/Online: Sites Health Monitoring by PowerShell Automation

It is not uncommon that we need to perform health monitoring on SharePoint Sites to ensure that we have stable and healthy SharePoint Farms and to ensure maximum possible availability of all the sites.

In this article we will discuss a simple yet powerful automation technique using PowerShell that will try ping the Site and if gets failed it will send the email notifications to the designated SharePoint Admins for the Site.

With this background let’s start with the demo…

In this demo we have two SharePoint Sites in Question as follows-

The On-Premise site is up and running while SharePoint Online Site is down and unavailable due to some technical reasons

In order to automate this monitoring process I have written a simple function in PowerShell as explained below-

Step 1: Create an Object of System.Net.WebClient Class. This object will provide us the methods to deal with Site Pages

Step 2: Make use of DownloadString Method of this class to download the html of the respective Site Page

Step 3: Check for Possible Error Messages that SharePoint Page would generally contains in case of Site is not accessible by making use of Wild Card Search using Contains Method

Step 4 & 5: We are sending emails to the SharePoint Admins Informing that a specific site is down, so that they can take appropriate actions accordingly.


Step 6: This is the initiation function that is having an array of SharePoint Site URLs that requires monitoring.

Step 7: This function will call for Step 1 to Step 5 for each SharePoint Site URL in a periodic manner and keep on circulating the notifications in case of health issues with SharePoint Sites.


Once this automation script executes we can see the following email notification for SharePoint Online Site which is currenly down:


And there will be no emails for SharePoint On-Premise Site since it is healthy and active as shown below:


That is all for this demo.

Hope you find it helpful.