Category Archives: dot sourcing

Dot Sourcing variable and functions in Powershell

What I sometimes have trouble with is dot sourcing the ps1 files.  Dot sourcing a file allows the variables and functions to be available after the script has run.

A simple demo of this is to create a .ps1 file containing the following:

We then run this .ps1 file within powershell.  When we then try to use the variable $a, nothing happens, as the variable is removed when the script finishes.

To dot Source the file, use the command:
. .Test-DotSourcing.ps1
Notice the dot space dot backslash syntax.

The variable $a is now available within that session.

To use Dot sourcing with a function, consider the following function:

function test-DotSourcing2 {

We can use this by firstly Dot sourcing the .ps1 file as normal, then calling the function name directly (remove the .ps1 extension). 

The function name will also be available in tab completion.