. (source or dot operator)

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.

      . filename [arguments]

   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"
powershell -file c:\demo\script.ps1

In contrast, if you use the call operator (&) to run a function or script, it is not added to the current scope.


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
PS C:\> $n = 1;.{$n = 2};$n

#If dogs run free, why not me, Across the swamp of time?, My mind weaves a symphony, And tapestry of rhyme# ~ Bob Dylan


& 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

© Copyright SS64.com 1999-2015
Some rights reserved