When you dot source a script (or scriptblock), all variables and functions defined in the script (or scriptblock) will persist in the shell when the script ends.
Syntax . filename [arguments] .{ scriptblock } Key filename The path and filename of the script to run. arguments Any arguments for the script.
When a script is Dot-Sourced in the current scope, any functions, aliases, and variables that the script creates become available in the current scope.
To dot-source a library script in the same directory as the currently running script, we can use the $MyInvocation Automatic Variable to work out the directory (we can't always assume this will be the current directory):
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}
In PowerShell 3 and above this can be simplified to:
. "$PSScriptRoot\scripttorun.ps1"
To start PowerShell and dot source a script:
powershell -command ". c:\demo\script.ps1"
or
powershell -file c:\demo\script.ps1
Dot sourcing runs a function or script within the current scope.
unlike the call operator (&) which will run a function or script, but it is not added to the current scope.PS C:\> $x=1
PS C:\> &{$x=2};$x
1
PS C:\> . {$x=2};$x
2
Examples
Dot sourcing a script:
PS C:\> . C:\scripts\myscript.ps1
Dot sourcing a script in the current directory:
PS C:\> . ./script64.ps1
Contrast these two snippets of PowerShell using scriptblocks:
PS C:\> $n = 1;&{$n = 2};$n
1
PS C:\> $n = 1;.{$n = 2};$n
2
#If dogs run free, why not me, Across the swamp of time?, My mind weaves a symphony, And tapestry of rhyme# ~ Bob Dylan
Related PowerShell Cmdlets:
& Call Operator - execute a command, script or function.
PowerShell Operators - Syntax.
Run a PowerShell script - Syntax.
Invoke-Item - Invoke an executable or open a file.