. (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.

Syntax
      . filename [arguments]

Key
   filename    The path and filename of the script to run.

   arguments   Any arguments for the script.

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

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:

& (call) - Run a command script
PowerShell Operators - Syntax
Run a PowerShell script - Syntax
Invoke-Item - Invoke an executable or open a file


© Copyright SS64.com 1999-2014
Some rights reserved