what is dot-sourcing in Powershell

Dot-sourcing is a concept in PowerShell that allows you to reference code defined in one script.

When you writing large size of PowerShell scripts, then there always seems to come a time when a single script just isn’t enough.  If we working on large size of script then it important to keep your scripts Simple and Reusable, so you can keep your block of script as modular. The Dot-sourcing is a way to do just that. Making script as modular it also useful when requirment came for adding some more functionlaiyt in exting script. Other than building a module, dot-sourcing is a better way to make that code in another script available to you.

For example, let’s say I’ve got a script that has two functions in it. We’ll call this script CommunicateUser.ps1. Here i had created single module which contain the two functionality in single file which used for sending email and SMS to the customer.

CommunicateUser.ps1

function SendEmail {
param($EmailContent)
#Write your Logic here 
Write-Output "****************************************"
Write-Output "Sending Mail" $EmailContent
Write-Output "****************************************"
}`
function SentSMS {
param($SMSContent)
#Write your Logic here 
Write-Output "****************************************"
Write-Output "Sending SMS" $SMSContent
Write-Output "****************************************"
}

Now i had created another script called UpdateUser.ps1. Here we needs to invoke those functions for sending the information to user. The CommunicateUser.ps1 script is located on the root of my C drive, so we can just put a period followed by a space and then the path of the script like shown below.

UpdateUser.ps1

# My CommunicateUser.ps1 script were located on the root of my C drive, so I just put a period, followed by a space and then the path of the script.
. C:\Users\MYPC\Desktop\PowerShell\CommunicateUser.ps1
$mailContent = 'MAIL - Hi Welcome to dotnet-helpers.com'
$smsContent = 'SMS - Hi Welcome to dotnet-helpers.com'
# Method Name (SendEmail) Parameter Name (-EmailContent) Parameter Value ($mailContent)
SendEmail -EmailContent $mailContent
SentSMS -SMSContent $smsContent

To make those functions available in the same scope, let we invoked CommunicateUser.ps1 script now, so now SendEmail and SentSMS are now available in the scope for use.  To dot source a script is very simple. I’ll now dot source my functions script inside of my CommunicateUser.ps1 script.

OUTPUT:

 

What do you think?

I hope you have an idea of how to utilize the dot-sourcing concept in Powershell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.